【LeetCode】40. Implement strStr()

题目描述(Easy)

Implement strStr().

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

题目链接

https://leetcode.com/problems/valid-palindrome/description/

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().

算法分析

暴力匹配,时间复杂度O(m*n),空间复杂度O(1)

KMP算法,时间复杂度O(m+n),空间复杂度O(m)

提交代码(暴力求解):

class Solution {
public:
	int strStr(const string& haystack, const string& needle) {
		if (needle.empty()) return 0;
		const int N = haystack.size() - needle.size() + 1;
		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;
	}
};

提交代码(KMP):

class Solution {
public:
	int strStr(const string& haystack, const string& needle) {
		return kmp(haystack, needle);
	}

	void get_next(const string& pattern, int next[])
	{
		int i = 0, j = -1;
		next[0] = j;
		while (i < pattern.size())
		{
			if (j < 0 || pattern[i] == pattern[j])
            {
                ++i, ++j;
                next[i] = pattern[i] != pattern[j] ? j : next[j];
            }
				
			else
				j = next[j];
		}
	}

	int kmp(const string& text, const string& pattern)
	{
		int m = pattern.size();
		const int n = text.size();
		if (m == 0) return 0;
		int *next = new int[m + 1];

		get_next(pattern, next);

		int i = 0, j = 0;
		while (i < n && j < m)
		{
			if (j < 0 || text[i] == pattern[j])
			{
				++i, ++j;
			}
			else
			{
				j = next[j];
			}
		}

		delete[] next;

		return j == m ? i - j : -1;
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, string haystack, string needle, int expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	int result = s.strStr(haystack, needle);

	if(result == expected)
		printf("passed\n");
	else
		printf("failed\n");
}

int main(int argc, char* argv[])
{
	
	Test("Test1", string("hello"), string("ll"), 2);
	Test("Test2", string("aaaaa"), string("bba"), -1);
	Test("Test3", string("aabaaabaaac"), string("aabaaac"), 4);
	Test("Test4", string("aaaaaaaa"), string("aaaaab"), -1);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82345025