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

题目:在字符串中找子串,找到了返回子串开始的位置,找不到则返回-1。子串为空串返回0

思路:遍历字符串haystack,如果出现了needle[0],则在此位置上相后查找needle.size()-2个,如果没有出现不等的情况,匹配成功,返回i,出现了不匹配的情况,退出循环,在i+1的位置上继续遍历。代码如下:

class Solution {
public:
    int strStr(string haystack, string needle) {
		int len1 = haystack.size();
		int len2 = needle.size();
		if(len2>len1) //子串长度大于母串
			return -1;
		if(len2 == 0) //子串为空串
			return 0;
		else{
			for(int i=0;i<len1-len2+1;i++){ //不需要遍历到最后,在len1-len2位置之后的肯定没有匹配的
				if(haystack[i]==needle[0]){ //开始匹配
					int k;
					for(k=0;k<len2;k++){
						if(needle[k]!=haystack[i+k])
							break; //不匹配,跳出循环
					}
					if(k==len2)
						return i;//完全匹配,返回位置i
				}
			}
			return -1; //遍历结束,无匹配,返回-1			
		}	     
    }
};

AC,beats 98%

猜你喜欢

转载自blog.csdn.net/qq_29303759/article/details/81335033