題目:
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
解析:實現strStr()方法,給定字串haystack和needle,返回在haystack中第一次出現needle的位置。該題的一般解法非常簡單,將haystack中的每個字元開頭的子串和needle進行比對,如果相等即返回該字元開頭的子串。該演算法的時間複雜度為O(m*n),m為haystack的長度,n為needle的長度。
我用KMP演算法實現該字串比對問題,首先針對模式串needle求出它的next數組,然後再遍曆haystack字串。
Java AC代碼如下:
public class Solution {public String strStr(String haystack, String needle) {if (haystack == null || needle == null) {return null;}int[] next = getNext(needle);int pS = 0, pH = pS, pN = 0;while (pS + needle.length() <= haystack.length()) {if (pN == needle.length()) {return haystack.substring(pS);} else if (haystack.charAt(pS + pH) == needle.charAt(pN)) {pH++;pN++;} else if (next[pN + 1] == 0) {pH = pN = 0;pS++;} else {pH -= (pN - next[pN]);pS += (pN - next[pN]);pN = next[pN];}}return null;}public static int[] getNext(String needle) {int[] next = new int[needle.length() + 1];next[0] = -1;needle = '$' + needle;for (int i = 1; i < needle.length(); i++) {if (next[i - 1] == 0) {next[i] = needle.charAt(i) == needle.charAt(1) ? 1 : 0;} else {int before = next[i - 1];while (before != -1) {if (needle.charAt(before + 1) == needle.charAt(i)) {next[i] = before + 1;break;} else {before = next[before];}}}}return next;}}