问题描述:
给一包含大写字母和整数(从 0
到 9
)的字符串, 试写一函数返回有序的字母以及数字和。
参考:https://blog.youkuaiyun.com/zhaohengchuan/article/details/78781394
思路:
(1)遍历原字符串,如果为数字则添加到和中。如果为字符,则直接添加到新字符串。最后新字符串排序,并加上“和”。
(2)(参考文献中的思路)使用整数数组存放26个大写字母出现次数,使用string存放大写字母词典。遍历原字符串,如果是大写英文字母,则整数数组对应位置+1;如果是数字,则添加到和中。然后遍历整数数组(正好是按照从A到Z的顺序存放了其个数),如果不为0,则往新字符串末尾依次添加指定个数的大写英文字符。最后加上“和”。这个方法避免了新字符串排序操作,更快。
代码如下:
class Solution {
public:
/**
* @param str: a string containing uppercase alphabets and integer digits
* @return: the alphabets in the order followed by the sum of digits
*/
string rearrange(string &str) {
// Write your code here
if (str.empty()) return str;
int sum = 0;
string s = "";
for (char c: str) {
if (isalpha(c)) {
s += c;
} else {
sum += (int)(c - '0');
}
}
sort(s.begin(),s.end());
s += to_string(sum);
return s;
}
};