0
点赞
收藏
分享

微信扫一扫

KMP模式匹配算法解决问题——28.实现strStr

kiliwalk 2022-04-23 阅读 46
leetcodejava
class Solution {
        public int strStr(String haystack, String needle) {
    	int[]next;
		int n = haystack.length();
		int m = needle.length();
		if (m == 0) {
			return 0;//模式串为空时返回0
		}
		if (n == 0||n < m) {
			return -1;
		}
		next = getNext(needle);
		
		int i = 0, j = 0;
		while (i < n && j < m) {
			if (j == -1||haystack.charAt(i) == needle.charAt(j)) {
				i++;
				j++;				
			}else{
				j = next[j];
				if (n - i + 1 < m - j + 1) {//若字符串长度不够,则break不再比较
					break;
				}
			}
		}
		return j == m ? i - m : -1;
    }

    public int[] getNext(String pattern){
		int j = 0, k = -1;
		int[]next = new int[pattern.length()];
		next[0] = -1;
		while(j < pattern.length()-1){
			if (k == -1 || pattern.charAt(k) == pattern.charAt(j)) {
				j++;
				k++;
				if (pattern.charAt(k) == pattern.charAt(j)) {
					next[j] = next[k];
				}else
					next[j] = k;
			}
			else
				k = next[k];
		}
		return next;
	}
}
举报

相关推荐

0 条评论