Leetcode 第 254 场周赛(8.15)
1.5843. 作为子字符串出现在单词中的字符串数目
思路
观察题目是字符串匹配。发现测试点都不大。100左右,应该没必要kmp暴力就行。
step1 遍历patterns
step2 word一个个去匹配patterns里面的元素
step3 判断word和patterns子元素的每一个字母是否相同。不同就break。word长度不够了也break。两个break
step4 patterns子元素全部字母都过了之后代表没问题。cnt++要加上break因为patterns的这个元素已经ok了不需要再次判断。
- 即使是简单题用暴力的方法还是没有一次过。第一次的时候没有考虑到已经匹配到子串之后word就不用继续遍历的情况了。
- 后面进行修改完后的代码就过了ok那里就直接break掉。这样word就不继续搜索了。
- 暴力
class Solution {
public:
int numOfStrings(vector<string>& patterns, string word) {
int cnt = 0;
for(int i = 0 ; i < patterns.size() ; i++) {
if(patterns[i].length() > word.length()){
continue;
}
for(int j = 0; j < word.length(); j++){
if(word.length()-j < patterns[i].length()) break;
bool ok = true;
for(int k = 0; k< patterns[i].length();k++){
if(patterns[i][k] != word[j+k]){
ok = false;
break;
}
}
if(ok){
cnt++;
break;
}
}
}
return cnt;
}
};
- 官方的kmp
class Solution {
public:
int numOfStrings(vector<string>& patterns, string word) {
auto check = [](const string& pattern, const string& word) -> bool{
int m = pattern.size();
int n = word.size();
// 生成 pattern 的前缀数组
vector<int> pi(m);
for (int i = 1, j = 0; i < m; i++){
while (j > 0 && pattern[i] != pattern[j]){
j = pi[j - 1];
}
if (pattern[i] == pattern[j]){
++j;
}
pi[i] = j;
}
// 利用前缀数组进行匹配
for (int i = 0, j = 0; i < n; i++){
while (j > 0 && word[i] != pattern[j]){
j = pi[j - 1];
}
if (word[i] == pattern[j]){
++j;
}
if (j == m){
return true;
}
}
return false;
};
int res = 0;
for (const string& pattern : patterns){
res += check(pattern, word);
}
return res;
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/number-of-strings-that-appear-as-substrings-in-word/solution/zuo-wei-zi-zi-fu-chuan-chu-xian-zai-dan-wmsp4/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
2.5832. 构造元素不等于两相邻元素平均值的数组
思路
看到这类题构造特殊的序列的数组。排序一下。这道题的思路也很明确。不等于左右两边的均值。那我们只要构造左右两边都比中间大或者左右两边都比中间小的数组就可以了。
step1 原数组排序一下
step2 排完序的数组我要构造成中间小两边大或者是中间大两边小。两两为一组。然后交换,就从小大->大小。然后这两个数后面的那一组数肯定是大于这两个数的。所以就形成了大小大小…。显然这样的数组是满足的。
class Solution {
public:
vector<int> rearrangeArray(vector<int>& nums) {
sort(nums.begin(), nums.end());
for(int i = 0; i< nums.size() -1 ; i+=2) {
swap(nums[i],nums[i + 1]);
}
return nums;
}
};
- 后面看到还有人用随机来做。蒙特卡洛?好像也挺暴力的。