题目原型:
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
public String strStr(String haystack, String needle) {
if(needle.length()>haystack.length())
return null;
if(needle.equals("")||needle.length()==0)
return haystack;
int i,j,first = 0;
int start = 0;
for(i=0,j=0;i<haystack.length()&&j<needle.length();)
{
if(j==0)
start = i;
char ch1 = haystack.charAt(i);
char ch2 = needle.charAt(j);
if(ch1!=ch2)
{
i = start+1;
j = 0;
}
else
{
if(j==0)
first = i;
i++;
j++;
}
}
if(j==needle.length())
return haystack.substring(first);
else
return null;
}
原文:http://blog.csdn.net/cow__sky/article/details/20067759