leetcode C++ 28. 實現 strStr() 實現 strStr() 函數。 給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 need

一、C++

class Solution {
public:
	int strStr(string haystack, string needle) {
		if (needle.size() == 0)
			return 0;
		int res = -1;
		for (int i = 0; i < haystack.size(); i++)
		{
			for (int j = 0; j < needle.size(); j++) {
				if (haystack[i] != needle[j]) {
					break;
				}
				if (haystack.size() - i < needle.size())
					return -1;
				int temp = i;
				while (temp < haystack.size() && j < needle.size() && haystack[temp] == needle[j]) {
					temp++;
					j++;
				}
				if (j >= needle.size())
					return i;
				else
					break;
			}
		}
		return res;
	}
};

 

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