Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
实现String的index函数
实现比较简单, 但是需要注意细节:
public class Solution {
public int strStr(String haystack, String needle) {
if(null == haystack || null == needle) return -1;
if("".equals(needle)) return 0;
int neLen = needle.length();
int hayLen = haystack.length();
for(int i=0;i<=hayLen - neLen; i ++){
if(haystack.charAt(i) == needle.charAt(0)){
int j = 1;
for(;j<neLen;j++){
if(haystack.charAt(i + j) != needle.charAt(j)){
break;
}
}
if(j == neLen){
return i;
}
}
}
return -1;
}
}
但是讨论区大神写的就非常的简单漂亮, 还不容易出错 值得学习。
public int strStr(String haystack, String needle) {
for (int i = 0; ; i++) {
for (int j = 0; ; j++) {
if (j == needle.length()) return i;
if (i + j == haystack.length()) return -1;
if (needle.charAt(j) != haystack.charAt(i + j)) break;
}
}
}