Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
實現查找字符子串位置,未找到返回-1
//應該用KMP來做
public static int strStr(String haystack, String needle) {
if(haystack ==null || needle ==null){
return 0;
}
if(haystack.length()<needle.length() ){
return -1;
}
boolean isSuccess = true;
for (int i = 0; i <= haystack.length() - needle.length(); i++) {
for (int j = 0; j < needle.length(); j++) {
if(haystack.charAt(i+j)!=needle.charAt(j)){
isSuccess =false;
break;
}
}
if(isSuccess){
return i;
}else{
isSuccess = true;
}
}
return -1;
}