leetcode 28. Implement strStr()
2017-05-19 19:21
369 查看
问题:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
采用KMP模式匹配算法:主要参考 http://blog.csdn.net/v_july_v/article/details/7041827 public class Solution {
public static int[] getNext(String sub){
int[] next=new int[sub.length()];
int k=-1,j=0;
next[0]=-1;
while(j<sub.length()-1){
if(k==-1||sub.charAt(k)==sub.charAt(j)){
k++;
j++;
next[j]=k;
}else{
k=next[k];
}
}
return next;
}
public int strStr(String haystack, String needle) {
if(needle.equals(""))return 0;
if(haystack.equals(""))return -1;
int i=0,j=0;
int[] next=getNext(needle);
while(i<haystack.length()&&j<needle.length()){
if(j==-1||haystack.charAt(i)==needle.charAt(j)){
i++;
j++;
}else{
j=next[j];
}
}
if(j==needle.length()){
return i-j;
}else return -1;
}
}
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
采用KMP模式匹配算法:主要参考 http://blog.csdn.net/v_july_v/article/details/7041827 public class Solution {
public static int[] getNext(String sub){
int[] next=new int[sub.length()];
int k=-1,j=0;
next[0]=-1;
while(j<sub.length()-1){
if(k==-1||sub.charAt(k)==sub.charAt(j)){
k++;
j++;
next[j]=k;
}else{
k=next[k];
}
}
return next;
}
public int strStr(String haystack, String needle) {
if(needle.equals(""))return 0;
if(haystack.equals(""))return -1;
int i=0,j=0;
int[] next=getNext(needle);
while(i<haystack.length()&&j<needle.length()){
if(j==-1||haystack.charAt(i)==needle.charAt(j)){
i++;
j++;
}else{
j=next[j];
}
}
if(j==needle.length()){
return i-j;
}else return -1;
}
}
相关文章推荐
- LeetCode 28. Implement strStr()
- LeetCode 28. Implement strStr()(字符串匹配问题)
- leetcode-28. Implement strStr()
- [Leetcode] 28. Implement strStr() 解题报告
- [LeetCode] 28. Implement strStr() ☆
- [leetcode]28. Implement strStr()
- 【leetcode】28. Implement strStr()(easy) KMP算法
- [leetcode] 28. Implement strStr()
- leetcode 28. Implement strStr()
- leetcode 28. Implement strStr()
- LeetCode-28. Implement strStr()
- [LeetCode]28. Implement strStr()
- LeetCode 28. Implement strStr()
- [勇者闯LeetCode] 28. Implement strStr()
- 【Leetcode】:28. Implement strStr()问题 in JAVA
- LeetCode 28. Implement strStr()
- LeetCode 28. Implement strStr()
- [LeetCode]28. Implement strStr()
- [LeetCode]28. Implement strStr()
- leetcode 28. Implement strStr()