给定一组只包含小写字母和’#‘的字符串, 求替换’#'之后字典序最小的字符串

如给出"m#efy###am", 第一个’#‘可以用a代替,因为它和m与e都不重复, 第二个’#‘号可以用a代替,与y不重复,第三个’#'用b代替,因为前一个已经替换成了a.
结果是maefyabcam


#!/usr/bin/python
# -*- coding:utf-8 -*-
import string


class Solution:

    @staticmethod
    def get_char(*args):
        for lowercase in string.ascii_lowercase:
            if lowercase in args:
                continue
            return lowercase

    @staticmethod
    def replace_string(input_str: str) -> str:
        length = len(input_str)
        if length == 1:
            return input_str if input_str != '#' else 'a'

        result = []
        for index, char in enumerate(input_str):
            if char != '#':
                result.append(char)
                continue
            elif index == 0:
                result.append(Solution.get_char(input_str[index + 1]))
            elif index == (length - 1):
                result.append(Solution.get_char(result[-1]))
            else:
                result.append(Solution.get_char(result[-1], input_str[index + 1]))

        return ''.join(result)


if __name__ == '__main__':
    input_string = "m#efy###am"
    print(Solution.replace_string(input_string))
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐