Interview questions 01.06 String Compression

Subject description:

String compression. Using the number of recurring characters, written in a way to achieve the basic string compression. For example, the string aabcccccaaa becomes a2b1c5a3. If the string "compressed" not shorter, the original string is returned. You may assume the string contains only the case letters (a to z).

Example 1:

 输入:"aabcccccaaa"
 输出:"a2b1c5a3"

Example 2:

 输入:"abbccd"
 输出:"abbccd"

He explains : "abbccd" compressed as "a1b2c2d1", the string length is longer than the original.

Tip : string length in the range [0, 50000].


1 problem-solving ideas:

  1. Count the number of times the same character appears.
  2. Statistics adjacent to heavy character after character
  3. List together with a digital character, and then the resultant is converted to a string

Code 1:

class Solution(object):
    def compressString(self, S):
        if len(S) == 0:   # 当 S = ""时
            return S

        j = 0
        countj = 1
        temp = []
        temp2 = []
        for i in range(len(S)-1):
            if S[i] == S[i+1]:
                countj += 1
            else:
                temp.append(countj)
                j += 1
                countj = 1
        temp.append(countj)     # 依次统计相同字符出现的次数

        k = 0
        for i in range(len(S)-1):
            if S[i] != S[i+1]:
                k = i+1
                temp2.append(S[i])
        temp2.append(S[k])     # 依次去重相邻字符

        temp3 = []
        for i in range(len(temp)):
            temp3.append(temp2[i]+str(temp[i]))
        temp3 = ''.join(list(temp3))  # 将列表转换为字符串

		return temp3 if len(temp3) < len(S) else S

s = Solution()
S = "aabcccccaaa"
print(s.compressString(S))

2 problem-solving ideas:

The same character string compression method is to compress the number of times of consecutive characters appear +. If the string length after compression short, compressed string is returned, otherwise retain the original string, so we can simulate the process of building a string.


Code 2:

From: stay button official website

class Solution:
    def compressString(self, S: str) -> str:
        if not S:
            return ""
        ch = S[0]
        ans = ''
        cnt = 0
        for c in S:
            if c == ch:
                cnt += 1
            else:
                ans += ch + str(cnt)
                ch = c
                cnt = 1
        ans += ch + str(cnt)
        return ans if len(ans) < len(S) else S

s = Solution()
S = "aabcccccaaa"
print(s.compressString(S))

Title Source:
interview questions 01.06 string compression.

Published 333 original articles · won praise 36 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_43283397/article/details/104893254