Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
public class Solution {
public String strStr(String haystack, String needle) {
if(needle==null || needle.isEmpty()) {
return haystack;
}
if(haystack==null) {
return null;
}
for(int i=0;i<haystack.length();i++) {
if(haystack.length()-i>=needle.length()) {
int j = 0;
while(j<needle.length() && haystack.charAt(j+i)==needle.charAt(j)) {
j++;
}
if(j==needle.length()) {
return haystack.substring(i);
}
} else {
break;
}
}
return null;
}
}
没有评论:
发表评论