力扣307:
第二题:https://leetcode.cn/problems/largest-palindromic-number/
首先使用一个数组记录0-9出现的次数,在满足回文数的条件下,最大的数出现在最前面更好,所以从9开始添加数字,如果计数每超过2就可以在前面和后面个添加一个9,最中间会选择从9-0中最大的单个数字,即计数%2==1,由于不能有前导0,需要使用一个flag标记前面是否有数字,而且还可能存在全是0的情况,此时需要输出"0"。
class Solution {
public:
string largestPalindromic(string num) {
int n=num.size();
int a[10];
memset(a,0,sizeof(a));
for(int i=0;i<n;i++){
a[num[i]-'0']++;
}
int flag=0;
string result="",result2="";
for(int i=9;i>=0;i--){
for(int j=0;j<a[i]/2;j++){
if(i!=0)flag=1;
if(i==0&&!flag)break;
result+='0'+i;
}
}
result2 = result;
reverse(result2.begin(), result2.end());
for(int i=9;i>=0;i--){
if(a[i]%2==1){
result+='0'+i;
break;
}
}
if(result.size()==0)return "0";
return result+result2;
}
};
力扣85双周:
第二题:https://leetcode.cn/problems/time-needed-to-rearrange-a-binary-string/
从左到右,直接遍历。
class Solution {
public:
int secondsToRemoveOccurrences(string s) {
int res = 0;
for(int i = 0, cnt = 0; i < s.size(); ++i) {
if(s[i] == '0') ++cnt;
else if(cnt > 0) res = max(res + 1, cnt);
}
return res;
}
};