大纲
- 题目
- 地址
- 内容
- 解题
- 代码地址
题目
地址
https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/
内容
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = “sadbutsad”, needle = “sad”
Output: 0
Explanation: “sad” occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack = “leetcode”, needle = “leeto”
Output: -1
Explanation: “leeto” did not occur in “leetcode”, so we return -1.
Constraints:
- 1 <= haystack.length, needle.length <= 104
- haystack and needle consist of only lowercase English characters.
解题
这题就是找到第一个匹配的子串。没啥特殊的技巧,逐位对比就行了。唯一需要注意的是边界问题:
- 如果待查找串的长度超过原串,则没有搜索的必要,因为子串不会超过原串的长度。
- 搜索时不用搜索到原串的最后一位。只用搜索到原串长度减去子串长度得到的下标位。
#include <string>
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle) {
auto haystackSize = haystack.size();
auto needleSize = needle.size();
if (haystackSize < needleSize) {
return -1;
}
if (needleSize == 0) {
return 0;
}
for (auto i = 0; i < haystackSize - needleSize + 1; i++) {
bool found = true;
for (auto j = 0; j < needleSize; j++) {
if (haystack[i+j] != needle[j]) {
found = false;
break;
}
}
if (found) {
return i;
}
}
return -1;
}
};
代码地址
https://github.com/f304646673/leetcode/tree/main/28-Find-the-Index-of-the-First-Occurrence-in-a-String