题目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
思路与步骤:
两个字符串逐个字符比较,如果两个字符串第一个不同,则大的下标加1,小的不变,依次循环;
如果相同,则依次逐个比较后面的,全部相同则返回;如果不是全部相同,则小的下标重新设为0,大的在最开始的基础上前进1。
程序通过后,经过几次简化,最后写出了比较简洁的程序。
编程实现:
C程序:
int strStr(char* haystack, char* needle) {
int hslen = strlen(haystack), nlen = strlen(needle);
if(nlen == 0) return 0;
if(nlen > hslen) return -1;
int i=0, j=0;
while (i <= hslen - nlen){
if(haystack[i] != needle[j]) i++;
else{
while(haystack[i] == needle[j] && j < nlen-1){
i++;
j++;
}
if(j == nlen-1 && haystack[i] == needle[j]) return i-j;
else{
i = i-j+1;
j = 0;
}
}
}
return -1;
}
Java程序:
public class Solution {
public int strStr(String haystack, String needle) {
if(needle.length() == 0) return 0;
if(needle.length() > haystack.length()) return -1;
char[] hsChar = haystack.toCharArray();
char[] nChar = needle.toCharArray();
int i=0, j=0;
while (i <= haystack.length()-needle.length()){
if((hsChar[i] != nChar[j])) i++;
else{
while(hsChar[i] == nChar[j] && j<needle.length()-1){
i++;
j++;
}
if(j==needle.length()-1 && hsChar[i] == nChar[j]) return i-j;
else{
i = i-j+1; //注意这里
j = 0;
}
}
}
return -1;
}
}
别人的简洁的算法(
还没看)效率并没有很高:
public class Solution {
public int strStr(String haystack, String needle) {
//别人的简洁方法,未看
for (int i = 0; ; i++) {
for (int j = 0; ; j++) {
if (j == needle.length()) return i;
if (i + j == haystack.length()) return -1;
if (needle.charAt(j) != haystack.charAt(i + j)) break;
}
}
}
}