説明
STRSTR()関数を実現します。
ストリング針干し草の山列が与えられると、針の位置は、干し草の山の文字列内の文字列(0から始まる)の最初の出現を検索します。ない場合は、-1を返します。
例
のアイデア
答え
- パイソン
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
len1=len(haystack)
len2=len(needle)
# i+len2-1=len1-1---i==len1-len2--i<len1-len2+1
for i in range(len1-len2+1):
if haystack[i:i+len2]==needle:
return i
return -1
- C ++
class Solution {
public:
int strStr(string haystack, string needle) {
int len1=haystack.size(),len2=needle.size();
// i+len2-1=len1-1---i==len1-len2--i<len1-len2+1
for (int i=0; i<len1-len2+1; i++)
if (haystack.substr(i,len2)==needle)
return i;
return -1;
}
};