【leetcode】443. String Compression
生活随笔
收集整理的這篇文章主要介紹了
【leetcode】443. String Compression
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目如下:
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
Follow up:
Could you solve it using only O(1) extra space?
Example 1:
?
Example 2:
?
Example 3:
?
Note:
?
解題思路:從頭到尾遍歷數組,記錄連續字符的個數,然后插入數組前部,注意每次插入要記錄當前的偏移量offset?。
代碼如下:
class Solution(object):def compress(self, chars):""":type chars: List[str]:rtype: int"""lastChar = Nonecount = 0inx = 0offset = 0chars.append('END') # terminatorwhile inx < len(chars):i = chars[inx]if lastChar == None:lastChar = icount = 1elif lastChar == i:count += 1else:lastOff = offsetchars.insert(offset,lastChar)offset += 1if count != 1:count = str(count)for j in count:chars.insert(offset, j)offset += 1lastChar = icount = 1inx += (offset - lastOff)inx += 1#print charsdel chars[-1]return offset?
轉載于:https://www.cnblogs.com/seyjs/p/9275563.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的【leetcode】443. String Compression的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hyphen Aria 空气传导耳机上架
- 下一篇: Canalys 报告:2023Q2 全球