Implement strStr

Implement strStr()

 

Implement strStr().

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

这里用的BF算法实现的,KMP待写...

 1 public class Solution {
 2     public int strStr(String haystack, String needle) {
 3         boolean found = true;
 4         int index = -1;
 5         if(0 == haystack.length() && 0 == needle.length())
 6             return 0;
 7         if(0 == haystack.length() && 0 == needle.length())
 8             return index;
 9         
10         for(int i = 0; i <= haystack.length() - needle.length(); i++){
11             int k = i;
12             found = true;
13             for(int j = 0; j < needle.length(); j++){
14                 if(haystack.charAt(k) == needle.charAt(j)){
15                     k++;
16                     continue;
17                 }
18                 else{
19                     j = 0;
20                     found = false;
21                     break;
22                 }
23             }//for
24             if(found){
25                 index = i;
26                 break;
27             }
28         }
29         
30         return index;
31     }
32 }

 今天看了一下KMP然后用KMP写了一个,思路还算清晰就是代码有点长

 1 public class Solution {
 2     public int strStr(String haystack, String needle) {
 3         int i = 0;
 4         int j = 0;
 5         int next[] = new int[needle.length()];
 6         if(haystack.length() == 0 && 0 == needle.length())
 7             return 0;
 8         if(needle.length() == 0)
 9             return 0;
10         if(0 == needle.length())
11             return - 1;
12         getNext(needle, next);
13         //showNext(next);
14         while(i < haystack.length() && j < needle.length()){
15             if(j == -1 || haystack.charAt(i) == needle.charAt(j)){
16                 i++;
17                 j++;
18             }
19             else{
20                 j = next[j];
21             }
22         }
23         if(j == needle.length())
24             return i - needle.length();
25         return  -1;
26     }
27         
28     /**
29      * 计算next[]的值
30      * @param pattern
31      * @param next
32      */
33     public void getNext(String pattern, int next[]){
34         int k = -1;
35         int j = 0;
36         next[0] = -1;
37         
38         while(j < pattern.length() - 1){
39             if(-1 == k || pattern.charAt(j) == pattern.charAt(k)){
40                 k++;
41                 j++;
42                 if(pattern.charAt(j) == pattern.charAt(k)){//如果两个相等,递推一下,少一次比较,优化后的代码
43                     next[j] = next[k];
44                 }
45                 else{
46                     next[j] = k;
47                 }
48             }
49             else{
50                 k = next[k];
51             }
52         }
53     }
54 }

 

posted on 2014-11-13 15:55  luckygxf  阅读(151)  评论(0编辑  收藏  举报

导航