LeetCode-Implement strStr()的一种算法
题目链接:https://leetcode.com/problems/implement-strstr/description/
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = “hello”, needle = “ll”
Output: 2
Example 2:
Input: haystack = “aaaaa”, needle = “bba”
Output: -1
题目要求我们找出haystack字符串中needle字符段的所在位置,存在返回该位置,否则返回-1。
算法很简单,先判断needle字符段是否为“”,是则直接返回0即可。随后判断haystack是否为“”且needle是否不为“”,是则返回-1。
而后循环遍历haystack的每一个字符,找到对应needle的第一个字符的字符位置,判断其是否等于needle,是则返回位置,否则继续循环遍历到最后。
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle == "") return 0; //判断
else if (haystack == "" && needle != "") return -1; //判断
for (int i = 0; i < haystack.length(); i++) { //循环遍历
if (haystack[i] == needle[0]) { //判断第一个字符是否相等
int j = needle.length();
//判断该位置开始的字符串是否存在与needle相同的部分
if (i+j <= haystack.length() && haystack.substr(i, j) == needle) {
return i;
}
}
}
return -1;
}
};
整个算法难度不大,麻烦的地方在于判断haystack或needle为“”的情况。