实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
第一种实现:使用equals
这个是一个简单题,解题的核心就是比较两个字符串是否相等,我想到的第一个办法就是使用java Api 实现,哈哈哈,有Api不用干嘛不用。既然要比较两个字符串是否相等,字符串是引用对象,equals用起来,哈哈哈。
private int funny(String haystack, String needle){
int m = haystack.length();
int n = needle.length();
int index = 0;
while (m - index >= n){
// 核心代码,使用java Api equals
if (haystack.substring(index, index + n).equals(needle)){
return index;
}
index++;
}
return - 1;
}
执行一下,还不错。是所有结果中最好的
第二种实现:暴力匹配
暴力匹配,其实和方法一类似,不过不是使用equals,而是使用字符串比较的方式
// 暴力匹配, 解决办法很简单,直接两个字符串就行比较就行,相同就返回下标,不同直接返回-1
private int bf(String haystack, String needle){
int m = haystack.length() - 1;
int n = needle.length() - 1;
for (int i = 0; i <= m; i++ ){
// 如果剩余要匹配的字符串长度已经小于匹配字符串,后面的比较将没有意义,直接退出
if (m - i < n){
break;
}
int temp = 0;
while (temp <= n){
// 这个是暴力匹配的核心,比较两个字符串的每一个值是否相等
if (haystack.charAt(i + temp) != needle.charAt(temp)){
break;
}
temp++;
}
if (temp - 1 == n){
return i;
}
}
return - 1;
}
第三种解法:KMP
代码很简单,就是找到KMP匹配表,匹配表根据左右前缀找到最长公共字符串,然后放到数组里面。代码很简单,但是思想很复杂,需要重点关注KMP匹配表
// 最好的解法:KMP算法
private int KMP(String str1, String str2, int[] next){
for (int i = 0, j = 0; i < str1.length(); i++){
while (j > 0 && str1.charAt(i) != str2.charAt(j)){
j = next[j - 1];
}
if (str1.charAt(i) == str2.charAt(j)){
j++;
}
if (j == str2.length()){
return i - j + 1;
}
}
return - 1;
}
// KMP算法的前提:公共前缀匹配表
private int[] KPMTable(String needle){
int[] next = new int[needle.length()];
for (int i = 1, j = 0; i < needle.length(); i++){
// 核心
while (j > 0 && needle.charAt(i) != needle.charAt(j)){
j = next[j - 1];
}
if (needle.charAt(i) == needle.charAt(j)){
j++;
}
next[i] = j;
}
return next;
}