leetcode 28. Implement strStr() 实现 strStr()(简单)
LeetCode 实现 简单 28 Implement strstr
2023-09-11 14:22:52 时间
一、题目大意
实现 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
提示:
- 1 <= haystack.length, needle.length <= 104
- haystack 和 needle 仅由小写英文字符组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解题思路
思路1:此题可用KMP算法,可以o(m+n)时间利用动态规划完成。
思路2:遍历线字符串,只需要遍历m-n长度即可,这样可以提高运算效率。然后对每个字符,都遍历一遍子字符串,一个一个字符的对应比较,如果对应位置有不等的,则跳出循环,如果一直没有跳出循环,则说明子字符串出现了,返回起始位置即可。
三、解题方法
3.1 Java实现
public class Solution {
public int strStr(String haystack, String needle) {
int m = haystack.length();
int n = needle.length();
if (m < n) {
return -1;
}
for (int i = 0; i <= m - n; i++) {
int j;
for (j = 0; j < n; j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
break;
}
}
if (j == n) {
return i;
}
}
return -1;
}
}
四、总结小记
- 2022/8/30 工作啊,工作啊
相关文章
- Leetcode: H-Index
- leetcode 208. 实现 Trie (前缀树)
- LeetCode高频题:如何不用int转字符数组,实现int类型数字x的第L位和R位数字交换
- [LeetCode]709. 转换成小写字母
- [leetcode]Two Sum
- [LeetCode] 1125. Smallest Sufficient Team 最小的必要团队
- [LeetCode] 470. Implement Rand10() Using Rand7() 使用Rand7()来实现Rand10()
- [LeetCode] N-ary Tree Level Order Traversal N叉树层序遍历
- [LeetCode] Maximum Product of Three Numbers 三个数字的最大乘积
- [LeetCode] Design Compressed String Iterator 设计压缩字符串的迭代器
- [LeetCode] 288. Unique Word Abbreviation 独特的单词缩写
- [LeetCode] Implement Queue using Stacks 用栈来实现队列
- [LeetCode] 28. Implement strStr() 实现strStr()函数
- leetcode 15. 3Sum 三数之和(中等)
- leetcode算法28.实现strStr()