题目
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
来源:力扣(LeetCode)
解法一:(窗口移动)
思路
子串逐一比较:沿着子字符串的长度逐步移动滑动窗口,将窗口里的字符串和needle比较
代码
public static int strStr_1(String haystack, String needle) {
if(needle.equals("")) return 0;
int h_length = haystack.length();
int n_length = needle.length();
for (int i = 0; i < (h_length-n_length)+1; i++) {
if(haystack.substring(i,i+n_length).equals(needle)){
return i;
}
}
return -1;
}
结果
解法二:辅助下标List(和字串第一个字符串相等的下标)
思路
上一个方法的中会将haystack中所有和needle一样长度的字串比较,实际上我们只需要第一个字符相同才要比较
(1)用一个辅助的List用来存放,needle的第一个字符在haystack中位置下标
(2)遍历List中存的下标,在haystack截取字符串和needle比较
代码
public static int strStr_2(String haystack, String needle){
if(needle.equals("")) return 0;
int h_length = haystack.length();
int n_lengyh = needle.length();
List<Integer> s_index = new ArrayList();
for (int i = 0; i < (h_length-n_lengyh+1); i++) {
if(haystack.charAt(i) == needle.charAt(0)){
s_index.add(i);
}
}
for (int i = 0; i < s_index.size(); i++) {
if(haystack.substring(s_index.get(i),(s_index.get(i)+n_lengyh)).equals(needle)){
return s_index.get(i);
}
}
return -1;
}
结果
解法三:双指针
思路
(1)移动 ph 指针,直到 ph 所指向位置的字符与 needle 字符串第一个字符相等
(2)通过 ph,pn,cur_len 计算匹配长度
(3)如果完全匹配(即 cur_len == n_len),返回匹配子串的起始坐标(即 ph - n_len)
(4)如果不完全匹配,回溯。使 ph = ph - cur_len + 1, pn = 0, cur_len = 0
代码
public static int strStr_3(String haystack, String needle){
if(needle.equals("")){
return 0;
}
int h_len = haystack.length();
int n_len = needle.length();
int ph = 0;
while(ph < (h_len-n_len+1)){
while(ph < (h_len-n_len+1) && haystack.charAt(ph) != needle.charAt(0)) ++ph;
int pn = 0;
int cur_len = 0;
while (ph < h_len && pn < n_len && haystack.charAt(ph) == needle.charAt(pn)){
++cur_len;
++pn;
++ph;
}
if(cur_len == n_len) return ph - n_len;
ph = ph - cur_len + 1;
}
return -1;
}
结果