—— Implement strStr()

28、 Implement strStr()

字符串查找

對於一個給定的 source 字符串和一個 target 字符串,你應該在 source 字符串中找出 target 字符串出現的第一個位置(從0開始)。如果不存在,則返回 -1

樣例

如果 source = "source" 和 target = "target",返回 -1

如果 source = "abcdabcdefg" 和 target = "bcd",返回 1

我的代碼:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int h_len=haystack.length();
        int n_len=needle.length();
        if(n_len<1)return 0;//邊界(needle)爲空
        for(int i=0;i<h_len-n_len+1;i++)
            if(haystack[i]==needle[0])
                if(compare(haystack,needle,i))
                    return i;
        return -1;
    }
    bool compare(string haystack,string needle,int i)
    {
        int st=0;
        while(st<needle.length())
            if(haystack[i++]!=needle[st++])
                return false;
        return true;
    }
};

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章