原题入口
转载博文入口
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。
样例
样例 1:
输入: source = “source” , target = “target”
输出:-1
样例解释: 如果source里没有包含target的内容,返回-1
样例 2:
输入: source = “abcdabcdefg” ,target = “bcd”
输出: 1
样例解释: 如果source里包含target的内容,返回target在source里第一次出现的位置
//暴力匹配
public class Solution {
/**
* @param source:
* @param target:
* @return: return the index
*/
public int strStr(String source, String target) {
// Write your code here
int sLen = source.length();
int tLen = target.length();
for (int i = 0; i <= sLen - tLen; i++) {
int j;
for (j = 0; j < tLen; j++) {
if (target.charAt(j) != source.charAt(i + j)) {
break;
}
}
if (j == tLen) {
return i;
}
}
return -1;
}
}
//KMP算法
public class Solution {
/**
* @param source:
* @param target:
* @return: return the index
*/
public int strStr(String source, String target) {
// Write your code here
if (target.isEmpty()) return 0;
if (source.isEmpty()) {
if (target.isEmpty()) {
return 0;
} else {
return -1;
}
}
KMP kmp = new KMP(target);
return kmp.search(source);
}
}
class KMP {
private int[][] dp;
private String pat;
public KMP(String pat) {
this.pat = pat;
int M = pat.length();
// dp[状态][字符] = 下个状态
dp = new int[M][256];
// base case
dp[0][pat.charAt(0)] = 1;
// 影子状态 X 初始为 0
int X = 0;
// 构建状态转移图(稍改的更紧凑了)
for (int j = 1; j < M; j++) {
for (int c = 0; c < 256; c++)
dp[j][c] = dp[X][c];
dp[j][pat.charAt(j)] = j + 1;
// 更新影子状态
X = dp[X][pat.charAt(j)];
}
}
public int search(String txt) {
int M = pat.length();
int N = txt.length();
// pat 的初始态为 0
int j = 0;
for (int i = 0; i < N; i++) {
// 计算 pat 的下一个状态
j = dp[j][txt.charAt(i)];
// 到达终止态,返回结果
if (j == M) return i - M + 1;
}
// 没到达终止态,匹配失败
return -1;
}
}