Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
我的初始思路:先在haystack里找到needle的第一个字符,若找到,继续比较haystack的余下字符和needle的余下字符。若有字符不相等,则返回null。代码如下:
public class Solution {
public String strStr(String haystack, String needle) {
if(needle == "") return haystack;
int i = 0;
int j = 0;
char first = needle.charAt(j);
while(i < haystack.length()){
if(haystack.charAt(i) != first){
i++;
}
else break;
}
if(i == haystack.length()) return null;
while(i < haystack.length() && j < needle.length()){
if(haystack.charAt(i) != needle.charAt(j)) return null;
else{
i++;
j++;
}
}
if(i == haystack.length() && j < needle.length()) return null;
return needle;
}
}
这个思路是错误的。因为即使haystack和needle的余下字符不等,在haystack里找到一个新的位置,使它等于needle.charAt(0),还是有可能找到相等的。比如haystack = "abcaecd", needle = "cd".。按我这个思路,当找到c = c, 我们发现a (in haystack) != d in needle,于是返回null.
Approach I: Brute-fore
”假设原串的长度是n,匹配串的长度是m。思路很简单,就是对原串的每一个长度为m的字串都判断是否跟匹配串一致。“
Ref: http://blog.csdn.net/linhuanmars/article/details/20276833
public class Solution {
public String strStr(String haystack, String needle) {
//to compare each block (size = needle size) of haystack with needle
if(haystack == null || needle == null || needle.length() == 0){
return haystack;
}
if(needle.length() > haystack.length()){
return null;
}
for(int i = 0; i <= haystack.length() - needle.length(); i++){
boolean flag = true;
for(int j = 0; j < n; j++){
if(haystack.charAt(i + j) != needle.charAt(j)){
flag = false;
break;
}
}
if(flag == true) return haystack.substring(i);
}
return null;
}
}
Approach II: http://blog.csdn.net/linhuanmars/article/details/20276833
Note: My submission @https://oj.leetcode.com/submissions/detail/20217240/ has errors:
- my for loop (below) looks different from linhua's, but essentially they are the same.
for(int j = 0; j < haystack.length() - needle.length(); j++){
hayHash = (hayHash - tmpBase*haystack.charAt(j)) * base + haystack.charAt(j+needle.length());
if(hayHash == needleHash){
return j+1;
}
}
- The only thing that causes error is: set hashcode type to "long" not "int".