首页 > 试题广场 >

删除多余的字符得到字典序最小的字符串

[编程题]删除多余的字符得到字典序最小的字符串
  • 热度指数:1762 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给一个全是小写字母的字符串str,删除多余字符,使得每种字符只保留一个,并且让最终结果字符串字典序最小。

输入描述:
输入包含一行字符串,代表str


输出描述:
输出一行,代表删除后的字符串。
示例1

输入

acbc

输出

abc
示例2

输入

dbcacbca

输出

dabc

备注:
时间复杂度,额外空间复杂度
#data_in = input()
data_in = "cbbcbbcbcca"

def drawer(data_in):
    """用一个抽屉有序保存检测到的字母"""
    dr = [""]*26
    for i in data_in:
        index = ord(i) - ord("a")
        if not dr[index]:
            dr[index] = chr(ord("a")+index)
    print("".join(dr))

drawer(data_in)


编辑于 2021-01-25 15:03:58 回复(0)
if __name__ == '__main__':
    test_data = input()
    # test_data = 'dbcacbca'
    
    output = ''
    visual = [0, ] * 256
    record = [0, ] * 256
    
    # build record
    for vl in test_data:
        record[ord(vl)] = record[ord(vl)] + 1
        
    # filter    
    for vl in test_data:
        record[ord(vl)] = record[ord(vl)] - 1
        
        if visual[ord(vl)] == 1:
            continue
        
        while len(output) > 0 and output[-1] > vl and record[ord(output[-1])] > 0:
            visual[ord(output[-1])] = 0
            output = output[:-1]
        
        output  = output + vl
        visual[ord(vl)] = 1
        
    print(output)    

测试案例全通过,时间复杂度O(n)O(n),额外空间复杂度O(1)O(1)
编辑于 2020-05-26 22:22:39 回复(0)