【KMP&字符串匹配】Implement strStr()
2014-04-16 20:50
393 查看
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
解法一:简单遍历超时
解法二:KMP,看懂了,下次又忘了。。。
public class Solution {
public String strStr(String haystack, String needle) {
if(needle == null || haystack == null) return null;
int lenh = haystack.length();
int lenn = needle.length();
if(lenn == 0) return haystack;
int res = kmpFunc(haystack, needle);
if(res == -1) return null;
return haystack.substring(res);
}
public int[] compute(String p){
int m = p.length();
int b[] = new int[m];
b[0] = -1;
int k = -1;
for(int i = 1; i<m; i++){
while(k >= 0 && p.charAt(k+1) != p.charAt(i)){
k = b[k];
}
if(p.charAt(k+1) == p.charAt(i)) k++;
b[i] = k;
}
return b;
}
public int kmpFunc(String t, String p){
int n = t.length();
int m = p.length();
int []next = compute(p);
int q = -1;
for(int i=0; i<n; i++){
while(q>=0 && p.charAt(q+1) != t.charAt(i)){
q = next[q];
}
if(p.charAt(q+1) == t.charAt(i)) q++;
if(q == m-1){
return i-m+1;
}
}
return -1;
}
}
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
解法一:简单遍历超时
public class Solution { public String strStr(String haystack, String needle) { if(needle == null || haystack == null) return null; int lenh = haystack.length(); int lenn = needle.length(); String res = null; for(int i=0; i<lenh; i++){ res = haystack.substring(i, lenh); if(res.startsWith(needle)) return res; } return null; } }
解法二:KMP,看懂了,下次又忘了。。。
public class Solution {
public String strStr(String haystack, String needle) {
if(needle == null || haystack == null) return null;
int lenh = haystack.length();
int lenn = needle.length();
if(lenn == 0) return haystack;
int res = kmpFunc(haystack, needle);
if(res == -1) return null;
return haystack.substring(res);
}
public int[] compute(String p){
int m = p.length();
int b[] = new int[m];
b[0] = -1;
int k = -1;
for(int i = 1; i<m; i++){
while(k >= 0 && p.charAt(k+1) != p.charAt(i)){
k = b[k];
}
if(p.charAt(k+1) == p.charAt(i)) k++;
b[i] = k;
}
return b;
}
public int kmpFunc(String t, String p){
int n = t.length();
int m = p.length();
int []next = compute(p);
int q = -1;
for(int i=0; i<n; i++){
while(q>=0 && p.charAt(q+1) != t.charAt(i)){
q = next[q];
}
if(p.charAt(q+1) == t.charAt(i)) q++;
if(q == m-1){
return i-m+1;
}
}
return -1;
}
}
相关文章推荐
- zk zk studio
- eclipse中最常用的快捷键
- 最短路模板总结
- C#中的数据类型装换
- 利用腾讯企业邮箱开放API获取账户未读邮件数初探
- String VS Cstring(字符串)
- 导出EXCEL报错:NullPointerException
- 笔记之Ruby(二)
- saturate_cast的作用
- Monkey学习
- cocos2d-x 发布 android 版本心得
- C++继承与派生 笔记
- [翻译] FTCoreText
- 一步步学会使用SeaJS(转)
- 【转】java序列化技术
- java数组并集/交集/差集(补集)
- java UNIX时间戳的应用
- JNI 中文转码问题
- ZigBee帮助wifi设备选择信道的实验总结
- fingerGgesture