BUUCTF刷題記錄(更新中...)
阿新 • • 發佈:2022-05-21
LeetCode 28. Implement strStr() (實現 strStr())
題目
連結
問題描述
給你兩個字串 haystack 和 needle ,請你在 haystack 字串中找出 needle 字串出現的第一個位置(下標從 0 開始)。如果不存在,則返回 -1 。
說明:
當 needle 是空字串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。
對於本題而言,當 needle 是空字串時我們應當返回 0 。這與 C 語言的 strstr() 以及 Java 的 indexOf() 定義相符。
示例
輸入:haystack = "hello", needle = "ll"
輸出:2
提示
1 <= haystack.length, needle.length <= 104
haystack 和 needle 僅由小寫英文字元組成
思路
字串匹配,採用kmp演算法可以減少複雜度。
複雜度分析
時間複雜度 O(m+n)
空間複雜度 O(m)
程式碼
Java
public int strStr(String haystack, String needle) { if (needle.isEmpty()) { return 0; } int n = haystack.length(), m = needle.length(); haystack = " " + haystack; needle = " " + needle; char[] s = haystack.toCharArray(); char[] p = needle.toCharArray(); int[] next = new int[m + 1]; for (int i = 2, j = 0; i <= m; i++) { while (j > 0 && p[i] != p[j + 1]) { j = next[j]; } if (p[i] == p[j + 1]) { j++; } next[i] = j; } for (int i = 1, j = 0; i <= n; i++) { while (j > 0 && s[i] != p[j + 1]) { j = next[j]; } if (s[i] == p[j + 1]) { j++; } if (j == m) { return i - m; } } return -1; }