题目描述:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
其实就是要实现一个查找子字符串起始位置的函数。
思路:
本文采用的是传统解法,两层遍历,对于字符串haystack的逐个字符往后移动,判断haystack[i...needle.Length]是否等于needle即可。
更快的算法是KMP,这两篇文章讲的非常清楚:
http://blog.csdn.net/v_july_v/article/details/7041827
http://www.ruanyifeng.com/blog/2013/05/Knuth–Morris–Pratt_algorithm.html
实现代码:public class Solution {
public int StrStr(string haystack, string needle) {
var i = 0;
while(i < haystack.Length - needle.Length + 1){
var k = i;
while(k < haystack.Length - needle.Length + 1){
var s = haystack.Substring(k, needle.Length);
if(s == needle){
return k;
}
k++;
}
i++;
}
return -1;
}
}