【题目】28. 实现 strStr()
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
【解题思路1】
双指针,i指向haystack,j指向needle,将needle的首字符依次和haystack的字符比较,比较到一样时比对needle后面的字符,注意内循环 i+j 才是haystack的位置
class Solution {
public int strStr(String haystack, String needle) {
int i,j;
int n = haystack.length(), m = needle.length();
for(i=0; i<n-m+1; i++){
for(j=0; j<m; j++){
//为了保证在这个循环里haystack的索引也跟着needle索引一起向前推进,i的含义设置为起始点,i+j才是haystack的索引
if(haystack.charAt(i+j) != needle.charAt(j))
break;
}
if(j == m)
return i;
}
return -1;
}
}
【解题思路2】
KMP(暂时还没研究)
class Solution {
public int strStr(String haystack, String needle) {
if(needle.equals("")) {
return 0;
}
if(haystack.equals("")) {
return -1;
}
// 构造KMP中的dp矩阵
int m = needle.length();
// 各个状态(行)遇到下一个字符(列)跳转到哪个状态
int[][] dp = new int[m][256];
// 影子状态
int X = 0;
dp[0][needle.charAt(0)] = 1;
for (int i = 1; i < m; i++) {
for (int j = 0; j < 256; j++) {
//假设下个字符不匹配,此时要回去看影子状态,从而得知跳转到哪个状态
dp[i][j] = dp[X][j];
}
// 只有pat上i的字符匹配,跳转到下个状态
dp[i][needle.charAt(i)] = i + 1;
// 更新影子状态
X = dp[X][needle.charAt(i)];
}
// 构造dp完成后,开始search
// 初始状态为0
int s = 0;
for (int i = 0; i < haystack.length(); i++) {
s = dp[s][haystack.charAt(i)];
if (s == m) {
return i - m + 1;
}
}
// 匹配失败,返回-1
return -1;
}
}
class Solution {
public int strStr(String haystack, String needle) {
int strLen = haystack.length(), subLen = needle.length();
if (subLen == 0) return 0;
if (strLen == 0) return -1;
// 构建状态机
int[][] FSM = new int[subLen][256];
int X = 0, match = 0;
for (int i = 0; i < subLen; i++) {
match = (int) needle.charAt(i);
for (int j = 0; j < 256; j++) {
// 当前状态 + 匹配失败字符 = 孪生词缀状态 + 匹配字符
FSM[i][j] = FSM[X][j];
}
FSM[i][match] = i + 1;
if (i > 0) { //这里根据评论>1修改为>0
// 下一孪生前缀状态 = X + match
X = FSM[X][match];
}
}
// 匹配子串
int state = 0;
for (int i = 0; i < strLen; i++) {
state = FSM[state][haystack.charAt(i)];
if (state == subLen) {
return i - subLen + 1;
}
}
return -1;
}
}