實現strStr()

實現 strStr() 函數。

給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回  -1

示例 1:

輸入: haystack = "hello", needle = "ll"
輸出: 2

示例 2:

輸入: haystack = "aaaaa", needle = "bba"
輸出: -1

說明:

當 needle 是空字符串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。

對於本題而言,當 needle 是空字符串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。

這題其實挺簡單,思路理清就可以,遍歷第一個字符串(其實只需要遍歷兩個字符串中字符個數之差就可以,n-m),依次與第二個字符串比較,如果不一樣就跳出,並判斷是否已經遍歷完第二個字符串;
自己的代碼如下;寫的複雜了,不夠好;
class Solution {
public:
    int strStr(string haystack, string needle) {
        int m=haystack.size();int n=needle.size();
        int i=0;int j=0;bool flat=true;int sign=0;
        if(n<1) return 0;
        if(m<1||m<n) return -1;
        while(i<m&&j<n)
        {
            if(haystack[i]==needle[j])
            {
                flat=compare(haystack,needle,i);
                if(flat)
                {
                    sign=i;
                    return sign;
                }
            }
            i++;
        }
        return -1;
    }
    bool compare(string s1,string s2,int i)
    {
        int h=s1.size();int k=s2.size();int it=1;int ix=i+1;
        while(it<k)
        {
            if(s1[ix]==s2[it])
            {
                it++;
                ix++;
                continue;
            }
            else
                return false;
        }
        return true;
    }
};

在網上看到精簡的(差距啊!心塞),代碼如下:

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

測試代碼:

int main()
{
	Solution temp;
	string s1 = "hello";string s2 = "llt";
	cout << temp.strStr(s1, s2) << endl;
	system("pause");
	return 0;
}

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