题目如下:
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 :
输入: haystack = “hello”, needle = “ll” 输出: 2
自己的思路:
如果直接用字符串函数可以直接匹配字符串。
如果用遍历来做,需要两个遍历来做
大神思路:
其实这是一个字符串匹配问题,可以用KMP算法
这里列出的是官网的暴力匹配
public int strStr(String haystack, String needle) {
int L = needle.length();
int n = haystack.length();
for (int start = 0; start < n - L + 1; start++) {
if (haystack.substring(start, start + L).equals(needle)) {
return start;
}
}
return -1;
}