28.实现strStr()Java
题目描述
实现 strStr() 函数。给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。当 needle 是空字符串时我们应当返回 0。
输入输出样式
示例1:
输入:haystack = “hello”, needle = “ll”
输出:2
示例2:
输入:haystack = “”, needle = “”
输出:0
本题来自LeetCode:https://leetcode-cn.com/problems/implement-strstr/
思路
遍历目标字符串,依次利用subString()判断是否包含needle。经典方法是KMP,很难,没看到,后面遇到希望有所突破。
算法分析
时间复杂度O(n * m),空间复杂度为O(1)
求解函数
public int strStr(String haystack, String needle) {
if (needle == null || needle.length() == 0) return 0;
int len1 = haystack.length();
int len2 = needle.length();
for (int i = 0; i <= len1 - len2; ++i) {
if (haystack.substring(i, i + len2).equals(needle)) {
return i;
}
}
return -1;
}