题目:实现strStr()
- 题号:28
- 难度:简单
- https://leetcode.cn/problems/implement-strstr/
实现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<=1041 <= haystack.length, needle.length <= 10^41<=haystack.length,needle.length<=104
haystack和needle仅由小写英文字符组成
实现
C# 语言
public class Solution
{
public int StrStr(string haystack, string needle)
{
if (string.IsNullOrEmpty(needle))
return 0;
for (int i = 0; i <= haystack.Length - needle.Length; i++)
{
int j = 0;
if (haystack[i] == needle[j])
{
for (j = 1; j < needle.Length; j++)
{
if (haystack[i + j] != needle[j])
break;
}
if (j == needle.Length)
return i;
}
}
return -1;
}
}
Python 语言
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle == '':
return 0
i = 0
while i <= len(haystack) - len(needle):
j = 0
if haystack[i] == needle[j]:
while j < len(needle):
if haystack[i + j] != needle[j]:
break
j += 1
if j == len(needle):
return i
i += 1
return -1
800

被折叠的 条评论
为什么被折叠?



