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.


思路:本題是讓找到一個字符串是不是另一個字符串的子串,如果是就返回下標,如果不是返回-1。暴力比較,時間複雜度:O(mn)。


C++代碼如下:

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