leetcode--28. Implement strStr()

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = “hello”, needle = “ll”
Output: 2
Example 2:

Input: haystack = “aaaaa”, needle = “bba”
Output: -1
Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

  • 題目描述
    實現strStr()
    返回haystack中第一次出現針的索引,如果針不是haystack的一部分,則返回-1。

  • 分析
    暴力解法:
    設置兩個變量,依次比較haystack 和 needle 各個字符,如果相等則進行下一個字符的比較
    遍歷haystack所以字符: 時間複雜度 O(n+m) 空間複雜度 O(1)

  • AC代碼

class Solution {
public:
    int strStr(const string haystack, const string needle) {
        if(needle.empty())  return 0;
        
        const int n=haystack.size()-needle.size()+1;
        if(n<=0) return 0;
        for(int i=0;i<n;++i){
            int j=i;
            int k=0;
            while(j<haystack.size() && k<needle.size() && haystack[j]==needle[k]){   
                //依次比較各個字符  相等則進行下一個比較
                j++;
                k++;
            }
            if(k==needle.size())  return i;
        }
        return -1;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章