Cracking the Coding Interview-1.6

第六版Cracking the Coding Interview题目1.6,题目如下:

String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).

这题主要考察Java中StringBuilder的概念。由于在Java中,尤其在循环中,使用+=连接字符串容易导致性能低下,所以在复杂情况下一般使用StringBuilder连接字符串。在Python中类似的是在字符串连接时先将字符串添加到list中再使用join函数连接。Python实现如下:

def stringCompression(str_):
    compressed = []
    counter = 0
    for i in range(len(str_)):
        if i != 0 and str_[i] != str_[i - 1]:
            compressed.append(str_[i - 1] + str(counter))
            counter = 0
        counter += 1
    compressed.append(str_[-1] + str(counter))
    return min(str_, ''.join(compressed), key=len)

注意的是根据不同的Python实现,字符串连接的复杂度是不同的,使用+=在CPython中大部分情况复杂度为O(n),但是在有些实现中(PyPy)也可能为O(n2),除了一些特殊情况以外,我们一般不需要考虑字符串连接导致的性能损失。具体说明可以参看这里


在手机上阅读或分享本文请扫描以下二维码:
By @Zhengyi Yang in
Tags : #cracking the coding interview, #python, #string,

Comments

评论功能已关闭。