28. Implement strStr()
最简单的方法,暴力找
1 public int strStr(String haystack, String needle) { 2 if(needle == null || needle.length() == 0) { 3 return 0; 4 } 5 if(haystack.length() < needle.length()) { 6 return -1; 7 } 8 for(int i = 0; i <= haystack.length()-needle.length(); i++) {//需要<= 9 int j = 0; 10 while(j < needle.length()) { 11 if(haystack.charAt(i+j) == needle.charAt(j)) { 12 j++; 13 } else { 14 break; 15 } 16 if(j == needle.length()) { 17 return i; 18 } 19 } 20 } 21 return -1; 22 }
bug记录:
1.第16行,错写成j == needle.length()-1,但是其实如果匹配,那么12行已经进行过j++此时应该是j == needle.length()