720. 重排带整数字符串

720. 重排带整数字符串

中文English

给一包含大写字母和整数(从 0 到 9)的字符串, 试写一函数返回有序的字母以及数字和.

样例

样例 1:

输入 : str = "AC2BEW3"
输出 : "ABCEW5"
说明 :
字母按字母表的顺序排列, 接着是整数的和(2 和 3)。

class Solution:
    """
    @param str: a string containing uppercase alphabets and integer digits
    @return: the alphabets in the order followed by the sum of digits
    """
    def rearrange(self, str):
        # Write your code here
        if str == '':
            return ''
        res_str = ''
        res_dig = 0
        while str != '':
            if str.isdigit() == True:
                break 
            res_str += max(str)
            str = str.replace(max(str),'',1)

        
        ##处理数字
        if str.isdigit() == True:
            for i in str:
                res_dig += int(i)
        return res_str[::-1] + '%s'%res_dig

大致思路:

1.如果str为空,则返回''

2.每次取出str最大的值,拼接到res_str中,只让它最后剩下数字(可能是纯字符串,不存在数字)

3.若存在数字的话,则进行求和,最后的时候拼接,返回值即可。

posted @ 2020-03-20 16:45  风不再来  阅读(169)  评论(0编辑  收藏  举报