Implement strStr()
My Submissions
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
坑有这么几个:
1.needle可能啥也没有.
2.可能needle 的长度大于 haystack
3.可以走着走着到最后了.
说白了,关键还是长度,长度,长度....
public class Solution {
public String strStr(String haystack, String needle) {
if (haystack == null){
return null;
}
if (needle == null || needle.equals("")){
return haystack;
}
if (needle.length() > haystack.length()){
return null;
}
int leng = 0;
for (int i = 0; i < haystack.length(); i++){
if (needle.charAt(0) == haystack.charAt(i)){
leng = needle.length() - 1;
for (int j = 1; j < needle.length(); j++){
if (i + j > haystack.length() - 1){
return null;
}
if (needle.charAt(j) == haystack.charAt(i + j)){
leng--;
}
}
if (leng == 0){
return haystack.substring(i);
}
}
}
return null;
}
}