28. 實現strStr()
阿新 • • 發佈:2018-08-18
als int com || nbsp 自己 stack ble 跳過
28. 實現strStr()
https://leetcode-cn.com/problems/implement-strstr/description/
竟然是KMP算法
自己寫的:
class Solution { public int strStr(String haystack, String needle) { if ("".equals(needle)) { return 0; } // 轉換為數組 char[] hayArray = haystack.toCharArray(); char[] needArray = needle.toCharArray(); // 從0開始進行判斷 for(int i=0;i<hayArray.length;i++) { // 如果第i個元素與needArray的第0個元素相等,就進行判斷 if (hayArray[i] - needArray[0] == 0) { boolean isEqual = true; // 判斷數組中是否有不相等的元素 for(int j=0;j<needArray.length;j++) {if (i + j >= hayArray.length) { isEqual = false; break; } if (hayArray[i + j] - needArray[j] != 0) { isEqual=false; } } // 如果都相等就返回i if(isEqual) { return i; } } } // 如果都不相等就返回-1 return -1; } }
KMP算法:
class Solution { public int strStr(String haystack, String needle) { if("".equals(needle)){ return 0; } char[] t = haystack.toCharArray(); char[] p = needle.toCharArray(); int i = 0; // 主串的位置 int j = 0; // 模式串的位置 int[] next = getNext(needle); while (i < t.length && j < p.length) { if (j == -1 || t[i] == p[j]) { // 當j為-1時,要移動的是i,當然j也要歸0 i++; j++; } else { // i不需要回溯了 // i = i - j + 1; j = next[j]; // j回到指定位置 } } if (j == p.length) { return i - j; } else { return -1; } } public static int[] getNext(String ps) { char[] p = ps.toCharArray(); int[] next = new int[p.length]; next[0] = -1; int j = 0; int k = -1; while (j < p.length - 1) { if (k == -1 || p[j] == p[k]) { if (p[++j] == p[++k]) { // 當兩個字符相等時要跳過 next[j] = next[k]; } else { next[j] = k; } } else { k = next[k]; } } return next; } }
28. 實現strStr()