重排带整数字符串

问题描述:

给一包含大写字母和整数(从 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;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值