声明:问题描述来自于leetcode
一、问题描述:
28. 实现 strStr()
难度:简单
实现 strStr() 函数。
给你两个字符串 haystack
和 needle
,请你在 haystack
字符串中找出 needle
字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1
。
说明:
当 needle
是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle
是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
示例 1:
输入:haystack = "hello", needle = "ll"
输出:2
示例 2:
输入:haystack = "aaaaa", needle = "bba"
输出:-1
示例 3:
输入:haystack = "", needle = ""
输出:0
提示:
1 <= haystack.length, needle.length <= 104
haystack
和needle
仅由小写英文字符组成
二、思路:
xin麒的第一感觉便是使用字符串的subString
函数截取和needle
一样长度大小的字符串str
,再和needle
使用equals比较,然后通过双指针的移动来更新str
不断比较,如果匹配成功就返回慢指针。
前提引入:
- len变量保存
needle
字符串的长度; - lenh变量保存
haystack
字符串的长度; - 变量start表示慢指针,变量end表示快指针(作用域为for循环体内)
- 字符串
str
为在haystack
中截取长度为needle.length()
的字符串;
过程:
- 先处理
hystack.length() < needle.length()
以及needle.length()
等于0的情况; - 通过一次遍历
for (int end = len; end <= lenh; end++)
,以慢指针start和快指针end截取到的字符串str与needle
使用equals作匹配,每一次匹配后都将start++,如果相同,慢指针(start - 1)
为所求,返回(start - 1)
即可。 - 如果没有找到可以匹配的,最终返回-1.
三、题解:
class Solution {
public int strStr(String haystack, String needle) {
int len = needle.length();
int lenh = haystack.length();
if (lenh < len || len == 0){
return -1;
}
int start = 0;
for (int end = len; end <= lenh; end++) {
String str = haystack.substring(start++, end);
if (str.equals(needle)){
return start - 1;
}
}
return -1;
}
}
运行:
如果是换作StringBuilder那么也一样的思路: