作者:disappearedgod
时间:2014-8-22
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
解法
采用了KMP算法,先构造DFA,然后查找DFA,最后返回一下begin=i - M的子串。
这里需要注意以下几点。
1.构造DFA[][]的维度:DFA[pattern中的字符数/pattern字符转化的整数值][patten长度]
查询DFA的i j:i 表示的是母体字符串的长度,j表示的是patten的长度。
2.构造DFA时候X的作用是:更新重启状态。
public class Solution {
public String strStr(String haystack, String needle) {
if(haystack.length() < needle.length())
return null;
if(haystack.length() < 2 || needle.length()==0)
return haystack;
//KMP
int M = needle.length();
int R = 256;
int[][] dfa = new int[R][M];
dfa[needle.charAt(0)][0] = 1;
for(int X = 0, j = 1; j < M; j++){
for(int c = 0; c < R; c++)
dfa[c][j] = dfa[c][X];
dfa[needle.charAt(j)][j] = j + 1;
X = dfa[needle.charAt(j)][X];
}
//search
int i = 0, j = 0;
int N = haystack.length();
for(; i < N && j < M ; i++)
j = dfa[haystack.charAt(i)][j];
if(j == M)
return haystack.substring((i-M));
else
return null;
}
}
结果是:
Submit Time | Status | Run Time | Language |
---|---|---|---|
0 minutes ago | Accepted | 932 ms | java |
public class Solution {
public String strStr(String haystack, String needle) {
if(haystack.length() < needle.length())
return null;
if(haystack.length() < 2 || needle.length()==0)
return haystack;
//KMP
int M = needle.length();
int R;
//find N
Map<Character, Integer> map = new HashMap<Character, Integer>();
int key = 0;
for(int i = 0 ; i < haystack.length() ; i++)
if(!map.containsKey(haystack.charAt(i)))
map.put(haystack.charAt(i), key++);
//assert
for(int j = 0 ; j < needle.length() ; j++)
if(!map.containsKey(needle.charAt(j)))
return null;
//
R = map.size();
int[][] dfa = new int[R][M];
dfa[map.get(needle.charAt(0))][0] = 1;
for(int X = 0, j = 1; j < M; j++){
for(int c = 0; c < R; c++)
dfa[c][j] = dfa[c][X];
dfa[map.get(needle.charAt(j))][j] = j + 1;
X = dfa[map.get(needle.charAt(j))][X];
}
//search
int i = 0, j = 0;
int N = haystack.length();
for(; i < N && j < M ; i++)
j = dfa[map.get(haystack.charAt(i))][j];
if(j == M)
return haystack.substring(i - M);
else
return null;
}
}
简化处理后时间少了1/3
Submit Time | Status | Run Time | Language |
---|---|---|---|
0 minutes ago | Accepted | 636 ms | java |
返回