版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83793289
题目:
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 whenneedle
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().
解释:
作弊的解法,内置库函数,注意不要用index()
,因为如果不存在的话,index()
会报错而find()
不会报错而是返回-1
。
python代码:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)
不作弊的写法,需要用在切片(子字符串)
python代码:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0;
n=len(haystack)
m=len(needle)
for i in range(n-m+1):
if haystack[i:m+i]==needle:
return i
return -1
c++代码:
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.size()==0)
return 0;
int m=needle.size();
int n=haystack.size();
for(int i=0;i<n-m+1;i++)
{
if (haystack.substr(i,m)==needle)
return i;
}
return -1;
}
};
总结:
使用子字符串,每次在haystack
中取和needle
长度一样的子字符串和needle
比较即可。