【LeetCode算法練習(C++)】Implement strStr()

題目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

鏈接:Implement strStr()
解法:兩重循環暴力求解。時間O(mn)

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

Runtime: 6 ms

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