Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
方法1:利用系统方法String.indexOf(),耗时6ms
public class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
方法2:自己写方法,耗时12ms,还不清楚可以怎么优化,可以看看官方怎么实现String.indexOf()方法的
public class Solution {
public int strStr(String haystack, String needle) {
int i=0; //haystack的指针
int j=0; //needle的指针
int len1=haystack.length();
int len2=needle.length();
int lastIndex=0; //上一个开始匹配的地方
boolean flag=false; //前一个是对是错
if(len2<1) return 0;
if(len1<1) return -1;
while(i<len1&&j<len2)
{
if(haystack.charAt(i)==needle.charAt(j))
{
if(j==(len2-1)) return i-j; //完全匹配
j++;
if(flag==false) lastIndex=i;
flag=true;
}
else
{
if(flag) i=lastIndex;//匹配不成功,返回到上一个开始匹配的地方
else lastIndex++;
j=0;
flag=false;
}
i++;
}
return -1;
}
}