28. 找出字符串中第一个匹配项的下标
KMP算法,先求Next数组,统一做减1操作
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.size() == 0)return 0;
// 求Next数组
vector<int> next(needle.size());
next[0] = -1;
for(int i = 1, j = -1; i < needle.size(); i++) { // 注意i从1开始
while (j >= 0 && needle[i] != needle[j + 1]) j = next[j]; // 向前回退
if (needle[i] == needle[j + 1]) j++; // 找到相同的前后缀
next[i] = j; // 将j(前缀的长度)赋给next[i]
}
for (int i = 0, j = -1; i < haystack.size(); i++) { // 注意i就从0开始
while(j >= 0 && haystack[i] != needle[j + 1]) { // 不匹配
j = next[j]; // j 寻找之前匹配的位置
}
if (haystack[i] == needle[j + 1])j++; // i的增加在for循环里
if (j == (needle.size() - 1) ) { // 文本串s里出现了模式串t
return (i - needle.size() + 1);
}
}
return -1;
}
};
1630. 等差子数组
对子数组排序后判断是否等差
class Solution {
public:
bool isArithmetic(vector<int>& nums) {
int n = nums.size();
if ((nums[n - 1] - nums[0]) % (n - 1) != 0) return false;
int sub = nums[1] - nums[0];
for (int i = 2; i < nums.size(); i++) {
if (nums[i] - nums[i - 1] != sub) return false;
}
return true;
}
vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) {
vector<bool> answer(l.size());
for (int i = 0; i < l.size(); i++) {
vector<int> tmp(nums.begin() + l[i], nums.begin() + r[i] + 1);
sort(tmp.begin(), tmp.end());
answer[i] = isArithmetic(tmp);
}
return answer;
}
};