Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
自己的代码:
public class Solution {
public int strStr(String haystack, String needle) {
for(int i=0;i<=haystack.length()-needle.length();i++){
boolean flag = true;
for(int j=0;j<needle.length();j++){
//只要有一个字符不匹配,则匹配失败
if(haystack.charAt(i+j)!=needle.charAt(j)){
flag = false;
break;
}
}
//若经过比较之后,flag==true,则匹配成功,返回i
if(flag==true){
return i;
}
}
return -1;
}
}