336. 文本压缩

336. 文本压缩

中文English

给你一个只含有可见字符(ASCII 码范围 3232 至 126126)文本文件,文件中可能出现一些重复的单词,你需要对它们进行压缩。
压缩规则如下:

  1. 如果原文件中的字符不是英文字符,那么保留这些字符。
  2. 我们将连续的英文字符视为一个单词,单词的前后不应该还有其它的英文字符。
    • 如果一个单词在它之前的文本中没有出现过,那么保留它。
    • 如果一个单词在它之前出现过,将其替换成前文中它第一次出现是第几个不同单词的编号。

样例

输入:
Please, please do it--it would please Mary very,
very much.

Thanks
输出:
Please, please do it--4 would 2 Mary very,
7 much.

Thanks

说明

样例中,please 是第 22 个出现的不同的单词,it 是第 44 个出现的不同的单词,very 是第 77 个出现的不同的单词。

注意事项

压缩中应该大小写敏感,"Abc" 和 "abc" 不是同一个单词。
文本中总的字符数为 NN,1 le N le 10^41N104​​。
一个单词不会跨行显示。

字符串切割 + 是否字符判断

class Solution:
    """
    @param lines: the text to compress.
    @return: return the text after compression.
    """
    def textCompression(self, lines):
        # write your code here.
        if not lines: return ''

        ss = '|'.join(lines) 

        s_dict, res = {}, ''
        count, index = 0, 0
        length = len(ss)

        while index < length:
            temp_s = ''
            if ss[index].isalpha():
                right = index
                while right < length and ss[right].isalpha():
                    temp_s += ss[right] 
                    right += 1
                
                #判断是否之前已存dict
                if temp_s not in s_dict.keys():
                    count += 1
                    s_dict[temp_s] = str(count)
                else:
                    temp_s = s_dict[temp_s]
                res += temp_s   

                #更新
                index = right
            else:
                res += ss[index]
                index += 1

        #格式矫正
        results = res.split('|')
        return results
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/14166213.html