0
点赞
收藏
分享

微信扫一扫

C++笔试题

幸福的无所谓 2022-04-16 阅读 59
c++

还是太菜了,好好努力吧✊🏻

正则表达式

力扣91题解码icon-default.png?t=M3C8https://leetcode-cn.com/problems/decode-ways/

class Solution {
public:
    int numDecodings(string s) {
        if(s[0] == '0')
            return 0;
        int size = s.size();
        int a = 1, b = 1, c = 0;
        for(int i = 1; i < size; i++)
        {
            c = b;
            if(s[i] == '0') //i位为0
            {
                if(s[i - 1] == '1' || s[i - 1] == '2') //看看能不能从前面找个凑
                {
                    b = a;
                }    
                else
                {
                    return 0;
                }  
            }
            else if(s[i-1] == '1'|| (s[i-1] == '2' && s[i] >= '1' && s[i] <= '6')) //只能是单独组成一个 s[i-1]=2 s[i]范围为1-6 
            { 
                 b = b + a; 
            }
            a = c;
            
        }
        return b;
    }
};

力扣28.实现strstr() 考KMP算法icon-default.png?t=M3C8https://leetcode-cn.com/problems/implement-strstr/

class Solution {
public:
    int strStr(string haystack, string needle) {
        int n = haystack.size();
        int m = needle.size();
        if(m == 0)
            return 0;
        //第一位设置为哨兵,字符串全部往后推进一位
        haystack.insert(haystack.begin(), ' ');
        needle.insert(needle.begin(), ' ');
        vector<int>  next(m+1);
        //预处理next数组
        for(int i = 2, j = 0; i <= m; i++){
            while(j and needle[i] != needle[j + 1]) 
                j = next[j];
            if(needle[i] == needle[j + 1]) 
                j++;
            next[i] = j;
        }
        //匹配过程
        for(int i = 1,j = 0; i <= n; i++)
        {
            while(j and haystack[i] != needle[j + 1])
                j = next[j];
            if(haystack[i] == needle[j + 1])
                j++;
            if(j == m)
                return i - m;
        }
        return -1;
    }
};
举报

相关推荐

0 条评论