原题
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
代码实现
public int StrStr(string haystack, string needle) {
int strh = haystack.Length, strn = needle.Length;
if(strn==0) return 0;
//i points to haystack
//j points to needle
for(int i=0; i<strh;i++ ){
int j=0;
for(j=0; j<strn && i<strh;){
if(haystack[i] == needle[j]){
// j = strn-1 indicates found first pattern
if(j==strn-1)
return i-j;
i++; j++;
}
else{
// haystack = "wsqazwsx" ; needle = "wsx"
if(j>0)
i=i-j; // only part pattern, directly moves to i-=j;
break;
}
}
}
return -1;
}
方法二:
利用 .NET 提供的API
public int StrStr(string haystack, string needle) {
return haystack.IndexOf(needle);
}
题库
Leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp