c_cpp 28.实现strStr()

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 28.实现strStr()相关的知识,希望对你有一定的参考价值。

//Runtime: 1632 ms, faster than 5.88%
//Memory Usage: 9.6 MB, less than 26.21%

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.length() == 0) return 0;
        
        int res;
        
        for(int i = 0;i < haystack.length();++i){
            int j = 0;
            res = i;
            while(haystack[i] == needle[j]){
                // cout << "i = " << i << " " << "j = " << j << endl;
                j++;i++;
                if(j == needle.length())
                    return i - needle.length();
            }
            i = res;
        }
        return -1;
    }
};

//Runtime: 2708 ms, faster than 5.01% 
//Memory Usage: 9.6 MB, less than 38.45%

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.length() == 0) return 0;
        
        int res;
        
        for(int i = 0;i < haystack.length();++i){
            int j = 0;
            res = i;
            bool m = true;
            while(haystack[i] == needle[j]){
                cout << "i = " << i << " " << "j = " << j << endl;
                j++;i++;
                if(haystack[res] == haystack[i] && m == true){
                    res = i - 1;
                    m = false;
                }
                    
                if(j == needle.length())
                    return i - needle.length();
            }
            i = res;
        }
        return -1;
    }
};
//Runtime: 8 ms, faster than 99.35%
//Memory Usage: 9.5 MB, less than 42.72%

class Solution {
public:
    int strStr(string haystack, string needle) {
        int m = haystack.size(),n = needle.size();
        for(int i = 0;i <= m -n;i++){
            int j = 0;
            for(;j < n;j++){
                if(haystack[i + j] != needle[j])
                    break;
            }
            if(j == n)
                return i;
        }
        return -1;
    }
};

以上是关于c_cpp 28.实现strStr()的主要内容,如果未能解决你的问题,请参考以下文章

28. 实现strStr()

[LeetCode] 28. Implement strStr() 实现strStr()函数

28. 实现 strStr()

leetcode 28. Implement strStr() 实现strStr()

28. 实现 strStr()

LeetCode#28 | Implement strStr() 实现strStr()