leetcode-implement-strstr 发表于 2017-01-20 | 分类于 算法 , leetcode | 题目大意 https://leetcode.com/problems/implement-strstr/ 实现字符串匹配判断 题目分析 利用kmp算法,具体原理可以看下我之前的一篇博客 代码12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455public class Solution { public int strStr(String haystack, String needle) { char[] txt = haystack.toCharArray(); char[] pat = needle.toCharArray(); int n = txt.length; int m = pat.length; if (n < m) { return -1; } if (n == 0) { return 0; } if (m == 0) { return 0; } int[] lps = new int[m]; // build lps array int preLen = 0; int i = 1; while (i < m) { if (pat[preLen] == pat[i]) { lps[i] = preLen + 1; i++; preLen++; } else { if (preLen == 0) { lps[i] = 0; i++; } else { preLen = lps[preLen - 1]; } } } // kmp i = 0; int j = 0; while (i < n) { if (txt[i] == pat[j]) { i++; j++; } if (j == m) { return i - j; } else if (i < n && txt[i] != pat[j]) { if (j > 0) { j = lps[j - 1]; } else { i++; } } } return -1; }}