本人编程小白,从今天开始,我将不定期更新《编程基础 0 到 1》板块
非常适合新手学习,我将分为三部分:
题目描述:
我的题解:
class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
直接调用函数解决(感觉是踩在巨人的肩膀上)
官方题解:
链接:https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/solutions/732236/shi-xian-strstr-by-leetcode-solution-ds6y/
方法一:暴力匹配
思路及算法
我们可以让字符串 needle\textit{needle}needle 与字符串 haystack\textit{haystack}haystack 的所有长度为 mmm 的子串均匹配一次。
为了减少不必要的匹配,我们每次匹配失败即立刻停止当前子串的匹配,对下一个子串继续匹配。如果当前子串匹配成功,我们返回当前子串的开始位置即可。如果所有子串都匹配失败,则返回 −1-1−1。
class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
for (int i = 0; i + m <= n; i++) {
boolean flag = true;
for (int j = 0; j < m; j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
flag = false;
break;
}
}
if (flag) {
return i;
}
}
return -1;
}
}