题目要求:
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
示例 1:
输入:haystack = “aaaaa”, needle = “bba”
输出:-1
示例 2:
输入:haystack = “”, needle = “”
输出:0
解题思路:要着重考虑当 needle 是空字符串时要输出什么,对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
代码如下:
class Solution {
public int strStr(String haystack, String needle) {
int m = haystack.length();
int n = needle.length();
if(n == 0) {
return 0;
}
int p = 0, q = 0, index = 0;
while(q < m && index < n) {
if(haystack.charAt(q) != needle.charAt(index)) {
p++;
q = p;
index = 0;
}else {
q++;
index++;
}
}
return index == n ? p : -1;
}
}
小结:
本题用到了双指针,其原理同昨天的20题,大家画出图就会好理解很多。
本题来模拟实现strStr()来加深对这个函数的理解,在平常写代码的过程中可直接使用C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。