Leetcode 28.实现strStr()
题目描述
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = “hello”, needle = “ll”
输出: 2
示例 2:
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
解题思路
方法一:
用needle字符串在haystack字符串上滑动匹配的方法,定义两个下标nIndex和hIndex,若是完全匹配,nIndex等于needle字符串的长度,这是hIndex就是要返回的下标。
class Solution {
public:
int strStr(string haystack, string needle) {
int needleLen = needle.length();
int haystackLen = haystack.length();
int hIndex = 0;
int nIndex = 0;
while(nIndex < needleLen) {
if ((hIndex+nIndex) >= haystackLen){
return -1; // 判断haystack上的索引是不是越界,若是,直接返回,没有相匹配的字符串
}
else if (needle[nIndex] == haystack[hIndex+nIndex]){
nIndex++; // 当前hIndex位置下,逐个的匹配元素。
}
else{
nIndex = 0; // 没有匹配,nIndex置位
hIndex++; // haystack位置向前移动一位
if(hIndex >= haystackLen){ // 没有找到,直接返回-1
return -1;
}
}
}
return hIndex;
}
};
方法二:使用c++中string的find方法,找到对应的字符串返回第一次出现的下标,否则返回string::npos
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack.find(needle) == string::npos){
return -1;
}
else{
return haystack.find(needle);
}
}
};
欢迎大家关注我的个人公众号,同样的也是和该博客账号一样,专注分享技术问题,我们一起学习进步