沙漠风网站建设每日一则小新闻
一、题目
有一个只含有 ‘Q’, ‘W’, ‘E’, ‘R’ 四种字符,且长度为 n 的字符串。
假如在该字符串中,这四个字符都恰好出现 n/4 次,那么它就是一个「平衡字符串」。
给你一个这样的字符串 s,请通过「替换一个子串」的方式,使原字符串 s 变成一个「平衡字符串」。
你可以用和「待替换子串」长度相同的 任何 其他字符串来完成替换。
请返回待替换子串的最小可能长度。
如果原字符串自身就是一个平衡字符串,则返回 0。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/replace-the-substring-for-balanced-string/description/
二、C++解法
我的思路及代码
最简单的思路,最屎的代码,简单的看下面的答案
采用滑动窗口的办法。用一个数组 count[4] 来存储每个字符出现的次数,遍历一次字符串获取到每一个字符出现的频率然后减去平均的次数放进数组,这样得到的数组中正数就是后面要与之进行比对的数字。再用一个数组 count1[4] 来表示当前滑动窗口内的字符出现的次数。再次遍历数组,每次判断窗口中的正数是否与 大于等于count 中的正数,若是则直接返回,若不是则继续循环,若遍历完成后没有返回,则增大窗口再次遍历,直到找到为止。
class Solution {
public:int balancedString(string s) {int temp = s.size()/4;int count[4]={-temp,-temp,-temp,-temp};int count1[4];int ans = 0;for(char it:s){switch(it){case 'Q':count[0]++;break;case 'W':count[1]++;break;case 'E':count[2]++;break;case 'R':count[3]++;break;}}if(count[0]==0&&count[1]==0&&count[2]==0&&count[3]==0){return 0;}for(int i=0;i<4;i++){if(count[i]>0)ans+=count[i];else count[i] = 0;cout<<count[i]<<endl; } //刚开始的窗口大小为正数之和,若当前窗口大小匹配失败,则窗口大小+1for(;ans<s.size()-ans;ans++){// cout<<ans<<endl; memset(count1,0,4*sizeof(int));for(int j=0;j<ans;j++){// cout<<j<<endl;switch(s[j]){case 'Q':count1[0]++;break;case 'W':count1[1]++;break;case 'E':count1[2]++;break;case 'R':count1[3]++;break;}}//判断是否可以返回了if(count[0]==0||count[0]<=count1[0])if(count[1]==0||count[1]<=count1[1])if(count[2]==0||count[2]<=count1[2])if(count[3]==0||count[3]<=count1[3])return ans;for(int j=0;j<s.size()-ans+1;j++){switch(s[j]){case 'Q':count1[0]--;break;case 'W':count1[1]--;break;case 'E':count1[2]--;break;case 'R':count1[3]--;break;}switch(s[j+ans]){case 'Q':count1[0]++;break;case 'W':count1[1]++;break;case 'E':count1[2]++;break;case 'R':count1[3]++;break;}//判断是否可以返回了if(count[0]==0||count[0]<=count1[0])if(count[1]==0||count[1]<=count1[1])if(count[2]==0||count[2]<=count1[2])if(count[3]==0||count[3]<=count1[3])return ans;} }return ans; }
};
- 时间复杂度:O(n^2),其中 n 为 s 的长度
- 空间复杂度:O(1)
官方参考代码
没看懂这个在写什么的,点击这里
class Solution {
public:int idx(const char& c) {return c - 'A';}int balancedString(string s) {vector<int> cnt(26);for (auto c : s) {cnt[idx(c)]++;}int partial = s.size() / 4;int res = s.size();auto check = [&]() {if (cnt[idx('Q')] > partial || cnt[idx('W')] > partial \|| cnt[idx('E')] > partial || cnt[idx('R')] > partial) {return false;}return true;};if (check()) {return 0;}for (int l = 0, r = 0; l < s.size(); l++) {while (r < s.size() && !check()) {cnt[idx(s[r])]--;r++;}if (!check()) {break;}res = min(res, r - l);cnt[idx(s[l])]++;}return res;}
};
- 时间复杂度:O(n),其中 n 为 s 的长度
- 空间复杂度:空间复杂度:O(∣Σ∣),其中 ∣Σ∣ 表示字符集大小,在本题中 ∣Σ∣=26