1.题目
实现 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
提示:
- 0 <= haystack.length, needle.length <= 5 * 104
- haystack 和 needle 仅由小写英文字符组成
2.答题
特别想试一下:haystack.indexOf(needle) 能不能把大神都秒了
思路1:
- 循环haystack,将haystack按照needle的长度拆分字符串作为key,循环位置i作为value,存放至Map中(重复则忽略)
- 根据Map中needle的value返回值,存在则返回value,不存在返回-1
- 特殊情况,needle长度为0,返回0
代码如下:
class Solution {
public int strStr(String haystack, String needle) {
int nLength = needle.length();
if (nLength == 0) {
return 0;
}
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i <= haystack.length() - nLength; i++) {
String str = haystack.substring(i, i + nLength);
if (!map.containsKey(str)) {
map.put(str, i);
}
}
Integer index = map.get(needle);
return index == null ? -1 : index;
}
}
额,我为什么要用Map存呢?!直接计算对比就好了
class Solution {
public int strStr(String haystack, String needle) {
int nLength = needle.length();
if (nLength == 0) {
return 0;
}
for (int i = 0; i <= haystack.length() - nLength; i++) {
String str = haystack.substring(i, i + nLength);
if (str.equals(needle)) {
return i;
}
}
return -1;
}
}
时间复杂度
遍历字符串O(n),hash表的插入、查询O(1)
空间复杂度
常量O(1)
提交结果
思路2:
-
循环haystack,对比当前循环的char与needle的第一个元素,
-
若不同,继续循环
-
若相同,开始两个指针顺序后移比较,
- 若直到needle最后匹配,返回当前位置的值
- 不能匹配,循环继续
-
特殊情况,needle长度为0,返回0
代码如下:
class Solution {
public int strStr(String haystack, String needle) {
int nLength = needle.length();
if (nLength == 0) {
return 0;
}
for (int i = 0; i <= haystack.length() - nLength; i++) {
if (haystack.charAt(i) != needle.charAt(0)) {
continue;
}
int j = 0;
boolean ret = true;
while (j < nLength) {
if (haystack.charAt(j + i) != needle.charAt(j)) {
ret = false;
break;
}
j++;
}
if (ret) {
return i;
}
}
return -1;
}
}
提交结果:
这个执行时间,想不出别的法了,有没有人能拯救一下我啊。。。。