一开始考虑出错,主要是因为它有一个子串的限制,就是要求子串是连续的。返回返回长度最小的子串长度。这个是错误的解法。
class Solution {
public:
int balancedString(string s) {
vector<int> cnt(4, 0);
for(int i=0;i<s.size();i++){
if (s[i]=='Q'){cnt[0]++;}
if (s[i]=='W'){cnt[1]++;}
if (s[i]=='E'){cnt[2]++;}
if (s[i]=='R'){cnt[3]++;}
}
int target = int(s.size()/4);
int res = 0;
for(int i=0;i<4;i++){
cout<<cnt[i]<<endl;
if (cnt[i]>target){
res += cnt[i]-target;
}
}
return res;
}
};
改成子串处理,对是对了,但是超时了,38/40
class Solution {
public:
int balancedString(string s) {
// gain all numbers
map<char, int> cnt;
for(int i=0;i<s.size();i++){
if (cnt.find(s[i])!=cnt.end()){
cnt[s[i]]++;
}
else{
cnt[s[i]] = 1;
}
}
int target = int(s.size()/4);
//if original is ok
if (cnt['Q']<=target&&cnt['W']<=target&&cnt['E']<=target&&cnt['R']<=target){
return 0;
}
// original is not ok, remove windows [i, j] and judge again
int res = s.size();
for(int i=0;i<s.size();i++){
map<char, int> cntnow = cnt;
for(int j=i;j<s.size();j++){
cntnow[s[j]] --;
if (cntnow['Q']<=target&&cntnow['W']<=target&&cntnow['E']<=target&&cntnow['R']<=target){
res = res < (j-i+1)? res: (j-i+1);
break;
}
}
}
return res;
}
};
看了别人的,真是学不来啊,佩服佩服
class Solution {
public:
int balancedString(string s) {
unordered_map<int, int> count;
int n = s.length(), res = n, i = 0, k = n / 4;
for (int j = 0; j < n; ++j) {
count[s[j]]++;
}
for (int j = 0; j < n; ++j) {
count[s[j]]--;
while (i < n && count['Q'] <= k && count['W'] <= k && count['E'] <= k && count['R'] <= k) {
res = min(res, j - i + 1);
count[s[i++]] += 1;
}
}
return res;
}
};
zeroQiaoba
发布了374 篇原创文章 · 获赞 18 · 访问量 15万+
私信
关注