28. 實現 strStr()(KMP演算法實現)
阿新 • • 發佈:2020-08-14
實現 strStr() 函式。
給定一個 haystack 字串和一個 needle 字串,在 haystack 字串中找出 needle 字串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
示例 1:
輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
KMP實現(速度非常慢)
class Solution { public int strStr(String haystack, String needle) { if(needle.length() == 0) return 0; int[] next = buildNext(needle); int m = next.length, i = 0; int n = haystack.length(), j = 0; while(j < n && i < m) { if(0 > i || haystack.charAt(j) == needle.charAt(i)) { i++; j++; } else { i = next[i]; } } return i == m ? j - i : -1; } public int[] buildNext(String needle) { int len = needle.length(), j = 0; int[] next = new int[len]; int t = next[j] = -1; while(j < len - 1) { if(0 > t || needle.charAt(j) == needle.charAt(t)) { j++; t++; next[j] = t; } else { t = next[t]; } } return next; } }
class Solution { public int strStr(String haystack, String needle) { if(needle == null || needle.length() == 0) return 0; int len_hs = haystack.length(); int len_n = needle.length(); int index = 0; int begin = 0; while(index < len_hs) { if(haystack.charAt(index) == needle.charAt(begin)) { index++; begin++; } else { if(begin > 0) { index = index - begin; begin = 0; } index++; } if(begin == len_n) return index - len_n; } return -1; } }
說明:
當 needle 是空字串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。
對於本題而言,當 needle 是空字串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/implement-strstr
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。