leetcode -- Implement strStr()

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

此题应用KMP算法来解,但忘记了,写了个普通解

line 10: 当needle == "" 时, 返回haystack

line 11: 循环终止条件需注意

 

 1 public class Solution {
 2     public static String strStr(String haystack, String needle) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         int needleLen = needle.length();
 6         int haystackLen = haystack.length();
 7         if (needleLen > haystackLen)
 8             return null;
 9 
10         if (needleLen == 0)
11             return haystack;
12             
13         int i = 0;
14         for (; i < haystackLen - needleLen + 1;) {
15             int j = 0;
16             for (; j < needleLen;) {
17                 if (needle.charAt(j) == haystack.charAt(i)) {
18                     i++;
19                     j++;
20                 } else {
21                     break;
22                 }
23             }
24             if (j == needleLen) {
25                 i = i - j;
26                 return haystack.substring(i, haystackLen);
27             } else {
28                 i = i - j + 1;
29             }
30 
31         }
32 
33         return null;
34     }
35 }

 

posted @ 2013-07-26 07:45  feiling  阅读(307)  评论(0编辑  收藏  举报