【LeetCode】28.實現strStr()
阿新 • • 發佈:2020-08-25
題目連結
28. 實現 strStr()
題目描述
實現 strStr() 函式。
給定一個 haystack 字串和一個 needle 字串,在 haystack 字串中找出 needle 字串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。
示例 1:
輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:
輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
解題思路
1.Java內建函式
2.BF暴力法
3.滑動視窗
利用substring函式從haystack依次擷取與needle字串相同長度的字串,兩者進行比較即可
4.KMP演算法
KMP演算法的核心就在於求解模式串的最長公共前後綴,且next陣列中next[0]=-1,next[1]=0是確定的,next陣列的意義在於當模式串當前字元與匹配串不匹配時,next陣列值就是模式串指標的下一個位置,而不是和暴力方法一樣,每次都從頭開始!
AC程式碼
1.Java內建函式
String haystack = "hellowordllo"; String needle = "llo"; System.out.println(haystack.lastIndexOf(needle));//9 System.out.println(haystack.indexOf(needle));//2 System.out.println(haystack.indexOf(needle,3));//9 a.indexOf(String s) //從字串a開始從前往後找到第一個與字元s匹配的子串,找到就返回匹配的子串的下標,否則返回-1 a.indexOf(String s,int Fromindex)//從字串a第Fromidnex個元素開始從前往後找到第一個與字元s匹配的子串,找到就返回匹配的子串的下標,否則返回-1 a.lastIndexOf(String s)//從後往前找
2.BF暴力法(超時)
class Solution { public int strStr(String haystack, String needle) { if(haystack.equals(needle)) return 0; if(haystack.length() < needle.length()) return -1; for(int i = 0; i < haystack.length(); i++){ int index = i; int cnt = 0; for(int j = 0; j < needle.length(); j++){ if(index < haystack.length() && needle.charAt(j) == haystack.charAt(index)){ index++; cnt++; } else break; } if(cnt == needle.length()) return i; } return -1; } }
3.滑動視窗
class Solution {
public int strStr(String haystack, String needle) {
if(haystack.equals(needle)) return 0;
if(haystack.length() < needle.length()) return -1;
int h_len = haystack.length();
int n_len = needle.length();
for(int i = 0; i <= h_len-n_len; i++){
String s = haystack.substring(i,i+n_len);
if(s.equals(needle)) return i;
}
return -1;
}
}
4.KMP演算法
//KMP演算法的核心在於求解next陣列
class Solution {
int[] getnext(String needle){
int[] next = new int[needle.length()];
next[0] = -1;
int l = -1;
int index = 0;
while(index < needle.length() - 1){
if(l == -1 || needle.charAt(l) == needle.charAt(index)){
l++;
index++;
next[index] = l;
}else l = next[l];
}
return next;
}
public int strStr(String haystack, String needle) {
if(haystack.length() == 0 && needle.length() == 0) return 0;
if(haystack.length() == 0) return -1;
if(needle.length() == 0) return 0;
int h_len = haystack.length();
int n_len = needle.length();
int h_index = 0;
int n_index = 0;
int[] next = getnext(needle);
while(h_index < h_len){
if(haystack.charAt(h_index) == needle.charAt(n_index)){
h_index++;
n_index++;
}else{
if(n_index == 0){//兩個字串首個元素不同,那匹配串指標肯定要加1呀
h_index++;
}else{
n_index = next[n_index];
}
}
//當模式串指標到模式串末尾,證明匹配成功
if(n_index == needle.length()) return h_index-n_index;
}
return -1;
}
}