Implement strStr()
来源:互联网 发布:单片机应用技术 编辑:程序博客网 时间:2024/05/01 07:02
Question:
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
//********** Hints ************
KMP算法详解: http://www.cnblogs.com/yjiyjige/p/3263858.html
//*****************************
Solution:
public class Solution {
public String strStr(String haystack, String needle) {
char[] n = needle.toCharArray();
char[] h = haystack.toCharArray();
assert(haystack!=null && needle!=null);
if(needle.length()==0) return haystack;
int[] next = getNext(needle);
int i = 0;
int j = 0;
while(i < haystack.length() && j < needle.length()){
if(j == -1 || n[j] == h[i]){
j++;
i++;
}
else{
j = next[j];
}
}
if(j == needle.length()){
return haystack.substring(i-j);
}
else
return null;
}
public int[] getNext(String s){
char[] target = s.toCharArray();
int[] next = new int[s.length()];
next[0] = -1;
int j =0;
int k = -1;
while(j < s.length() -1){
if(k== -1 || target[j] == target[k]){
next[++j] = ++k;
}
else{
k = next[k];
}
}
return next;
}
}
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- LeetCode - Combinations
- String to Integer
- 3Sum
- Valid Parentheses
- Merge Two Sorted List
- Implement strStr()
- 安装pvfs2
- Pow(x,n)
- Lesson 2: Udacity Intro to Parallel Programming
- liuru jia ACM训练指南链接(转载自BearChild blog)
- LeetCode - Merge k Sorted Lists
- 计算机视觉代码资源
- LeetCode - Generate Parentheses
- 小伙为挽回女友雨雪中跪地6小时