The idea is to loop the String and i < needle, s.length() - needle.length + 1, compare all possible cases.
public class Solution {
public String strStr(String haystack, String needle) {
if(needle == null || haystack == null || needle.length() > haystack.length()){
return null;
}
if(haystack.length() == 0 || needle.length() == 0){
return haystack;
}
for(int i = 0; i < haystack.length() - needle.length() + 1; i++){
for(int j = i; j < i + needle.length(); j++){
if(needle.charAt(j - i) != haystack.charAt(j)){
break;
}
if(j == i + needle.length() - 1 && needle.charAt(j - i) == haystack.charAt(j)){
return haystack.substring(i);
}
}
}
return null;
}
}
没有评论:
发表评论