【KMP&字符串匹配】Implement strStr()

Implement strStr().

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;
	}
}

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/wu_george/article/details/23874503
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞