题目要求匹配给定字符串和模式串,如果模式串存在于字符串中,则返回所在索引,如果不存在,则返回-1;
关于给定字符串和模式串的匹配问题,是数据结构的经典问题,也有其对应的解决算法,即KMP算法。然而数据结构中引出KMP算法也是为了解决暴力求解时,两个指针回溯问题,导致o(mn)的时间复杂度而提出的。
因此对于字符串的匹配,我们首先想到的就是暴力求解法。(*/ω\*)
一、暴力求解
思路:
* 逐个比较haystack[i]的每个字符和needle[0],如果对应的字符不
* 相等,则跳过。继续比较haystack[i+1],如果对应的字符相等,则继续比较haystack[i+1]和needle[1],一直比较到needle的
* 最后一个节点,如果needle[j]中的j等于needle的长度,说明找到了一个答案,直接返回i。
* 如果外层遍历完还是没找到,则返回-1。
java实现:
public int strStr(String haystack, String needle) {
if(needle.isEmpty()){
return 0;
}
int m=haystack.length();
int n=needle.length();
if(n>m) return -1;
for (int i = 0; i <=m-n; i++) {
int j=0;
for (; j < n; j++) {
if(haystack.charAt(i+j)!=needle.charAt(j)) break;
}
if(j==n) return i;
}
return -1;
}
另外一种方法:
* 1.当needle遍历到末尾,且每个字符都和haystack子串字符相同时,代表找到匹配的串。
* 2.在needle遍历过程中,当存在与haystack子串不同的字符时,需要重新获取haystack的子串进行匹配判断。
* 3.当haystack和needle恰好同时遍历到末尾时,还未找到匹配的串,则不存在匹配的串。
public int strStr2(String haystack,String needle){
for (int i = 0; ; i++) {
for (int j = 0; ; j++) {
//1.找到匹配的串
if(j==needle.length()) return i;
//3.当haystack和needle同时遍历完,还未找到匹配的串
if(i+j==haystack.length()) return -1;
//2.遍历过程中存在不相同的字符时,从haystack中重新截取子串进行匹配
if(needle.charAt(j)!=haystack.charAt(i+j)) break;
}
}
}
python实现:
二、KMP算法实现
和严蔚敏的数据结构的方法基本一致:重要的是求得模式串的next数组
java实现:
class Solution {
public int strStr(String haystack,String needle){
if(needle.isEmpty()){
return 0;
}
int i=-1,j=-1;
int m=haystack.length();
int n=needle.length();
int[] next=nextval(needle);
while(i<m&&j<n){
if(j==-1||(haystack.charAt(i)==needle.charAt(j))){
++i;
++j; //若相等,则继续向后比较
}
else{
j=next[j];//若不相等,则模式串向右移动
}
}
if(j>n-1){
return i-j; //匹配成功,返回索引
}
else return -1; //遍历成功,不存在,返回-1
}
public static int[] nextval(String sub){
int[] next=new int[sub.length()+1];
char[] T=sub.toCharArray();
int length=sub.length();
int k=-1;
int j=0;
next[0]=-1;
while(j<length-1){
if(k==-1||T[j]==T[k]){
k++;
j++;
if(T[j]!=T[k]){
next[j]=k;
}else{
next[j]=next[k];
}
}else{
k=next[k];
}
}
return next;
}