Implement strStr()

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

 1     public int strStr(String haystack, String needle) {
 2         if (haystack == null || needle == null) return -1;
 3         if (needle.length() == 0) return 0;
 4         if (needle.length() > haystack.length()) return -1;
 5         for (int i = 0; i <= haystack.length() - needle.length(); i++) {
 6             boolean isPass = true;
 7             for (int j = 0; j < needle.length(); j++) {
 8                 if (haystack.charAt(i + j) != needle.charAt(j)) {
 9                     isPass = false;
10                     break;
11                 }
12             }
13             if (isPass == true) {
14                 return i;
15             }
16         }
17         return -1;
18     }

 The key part is i <= haystack.length() - needle.length(); it is very easy to make mistake.

posted @ 2015-01-10 08:39  北叶青藤  阅读(123)  评论(0)    收藏  举报