刷点题吧。

建站前就丢这了。

 

 

28. 实现 strStr()

https://leetcode-cn.com/problems/implement-strstr/

KMP算法实现。C语言。

#include
#include

int nn[100000];
int i,j;
void preNeedle(char * needle, int ln){
	memset(nn, 0, sizeof(nn));
	nn[0]=0;
	for(i = 1; i < ln; i=i+1){
		int sl;
		sl = nn[i-1];
		while(1){
			if(needle[sl] == needle[i]){
				nn[i] = sl + 1;
				break;
			}else if(sl == 0){
				nn[i] = 0;
				break;
			}else{
				sl = nn[sl - 1];
			}
		}
	}
	/*for(i=0;i

备注: 复杂度O(m+n)。 测试数据水,暴力m*n也能过。

 

 

 

 

583. 两个字符串的删除操作

https://leetcode-cn.com/problems/delete-operation-for-two-strings/

LCS。 C语言。

#include
#include
#include
#define M 505
int l1,l2;
int i,j;
int dp[M][M];
int max(int a, int b){
    return a>b?a:b;
}
int minDistance(char * word1, char * word2){
    l1 = strlen(word1);
    l2 = strlen(word2);

    for(i=0;i

 

 

 

 

 

10. 正则表达式匹配

https://leetcode-cn.com/problems/regular-expression-matching/

递归+状态缓存。Python。

import functools
class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        self.s, self.p = list(s + '0'), list(p + '0')
        self.len_s, self.len_p = len(self.s), len(self.p)
        #print(s, p)
        return self.cmp(0, 0)

    @functools.lru_cache()
    def cmp(self, ls, lp):

        if(ls == self.len_s and lp == self.len_p): return True
        if(ls == self.len_s): return False
        if(lp == self.len_p): return False

        if(self.p[lp] == '*'): return False
        

        isNextAst = (lp + 1 < self.len_p and self.p[lp + 1] == '*')
        if(not isNextAst):
            if(self.p[lp] != self.s[ls] and self.p[lp] != '.'): return False
            return self.cmp(ls + 1, lp + 1)
        else:
            if(self.p[lp] != self.s[ls] and self.p[lp] != '.'): return self.cmp(ls, lp + 2)
            if(self.cmp(ls, lp + 2)): return True
            if(self.cmp(ls + 1, lp + 2)): return True
            return self.cmp(ls + 1, lp)

备注: 有了lru_cache()就不用手工二维数组[ls][lp]缓存了。

 

 

 

 

你可能感兴趣的:(刷点题吧。)