leetcode--28--实现 strStr()
2020-07-10 本文已影响0人
minningl
题目:
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
链接:https://leetcode-cn.com/problems/implement-strstr
思路:
1、采用滑动窗口的做法,从左往右遍历字符串haystack,如果任何位置往右 len(needle) 位置的字符串和needle全匹配的话,则识别匹配成功,否则返回-1
Python代码:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle == "":
return 0
m = len(haystack)
n = len(needle)
for i in range(m-n+1):
if haystack[i:i+n] == needle:
return i
return -1
C++代码:
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.size();
int n = needle.size();
if (n==0) return 0;
for (int i=0; i<m-n+1; i++){
if(haystack.substr(i, n) == needle) return i;
}
return -1;
}
};