LeetCode(28) - Implement strStr()

  这道题事实上就是编译一个String.indexOf()的函数,所以这道题直接用s1.indexOf(s2)便可解。但是这样做没有什么意义, 所以我们还是老老实实的一个一个遍历,当碰到首字母相同的时候,就判断加下来的字符串和needle是否相同,如果不相同,继续遍历。

  代码如下:

 1 public class Solution {
 2     public int strStr(String haystack, String needle) {
 3         if (needle.length() == 0) return 0;
 4         for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
 5             //如果首字母相同,check接下来needle长度的字符串是否和needle相同。
 6             if (haystack.charAt(i) == needle.charAt(0)) {
 7                 if (checkStr(haystack,i,needle)) return i;
 8             }
 9         }
10         return -1;
11     }
12     
13     private boolean checkStr(String haystack, int index, String needle) {
14         int needleIndex = 0;
15         while (needleIndex < needle.length()) {
16             if (haystack.charAt(index) != needle.charAt(needleIndex)) return false;
17             else {
18                 index++;
19                 needleIndex++;
20             }
21         }
22         return true;
23     }
24 }

 

posted @ 2016-03-16 12:08  可普CS之家  阅读(142)  评论(0编辑  收藏  举报