28.Implement strStr()---kmp

题目链接:https://leetcode.com/problems/implement-strstr/description/

题目大意:字符串匹配,从字符串中,找到给定字符串第一次出现的位置下标,并返回。

法一:暴力,两个for循环,逐一比较每一个可能的字符串,一旦找到,则返回。代码如下(耗时508ms->10ms):

 1     public int strStr(String haystack, String needle) {
 2         int res = -1, len_h = haystack.length(), len_n = needle.length();
 3         if(len_n == 0) {
 4             return 0;
 5         }
 6         //此处优化点:i <= len_h - len_n,当主字符串中字符个数已经过小时,则不需要再遍历了
 7         for(int i = 0; i <= len_h - len_n; i++) {
 8             //可能有当前字符串
 9             if(len_n != 0 && haystack.charAt(i) == needle.charAt(0)) {
10                 int k = i + 1, j = 1;
11                 boolean flag = true;
12                 for( ; j < len_n && k < len_h; j++) {
13                     if(haystack.charAt(k++) != needle.charAt(j)) {
14                         flag = false;
15                         break;
16                     }
17                 }
18                 if(flag == true && j == len_n) {
19                     res = i;
20                     break;
21                 }
22             }
23         }
24         return res;
25     }
View Code

法二(借鉴):kmp,练习一下kmp。代码如下(耗时20ms):

 1     public int strStr(String haystack, String needle) {
 2         int next[] = computeNext(needle);
 3         int i = 0, j = 0, len_h = haystack.length(), len_n = needle.length();
 4         for( ; i < len_h && j < len_n; i++) {
 5             while(j > 0 && haystack.charAt(i) != needle.charAt(j)) {
 6                 j = next[j - 1];
 7             }
 8             if(haystack.charAt(i) == needle.charAt(j)) {
 9                 j++;
10             }
11         }
12         return (j == needle.length()) ? (i - j) : -1;
13     }
14     private int[] computeNext(String needle) {
15         int[] next = new int[needle.length()];
16         for(int i = 1, j = 0; i < needle.length(); i++) {
17             while(j > 0 && needle.charAt(i) != needle.charAt(j)) {
18                 j = next[j - 1];
19             }
20             if(needle.charAt(i) == needle.charAt(j)) {
21                 j++;
22             }
23             next[i] = j;
24         }
25         return next;
26     }
View Code
原文地址:https://www.cnblogs.com/cing/p/8532739.html