[leetcode] 28.Implement strStr()

題目:
Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
題意:
實現strstr(),找到子串在原串中出現的第一個下標。
代碼如下:

class Solution {
public:
    int strStr(string haystack, string needle) {
        if (needle.empty())return 0;
        else if(haystack.empty())return -1;
        int needleSize = needle.length();
        int haystackSize = haystack.length();
        for (int i = 0; i <= haystackSize - needleSize; i++) {
            int j = 0;
            for (; j < needleSize; j++) {
                if (haystack[i + j] != needle[j])break;
            }
            if (j == needleSize)return i;
        }
        return -1;
    }
};
發佈了239 篇原創文章 · 獲贊 2 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章