題目描述
中文
給定一組字符,使用原地算法將其壓縮。
壓縮後的長度必須始終小於或等於原數組長度。
數組的每個元素應該是長度爲1 的字符(不是 int 整數類型)。
在完成原地修改輸入數組後,返回數組的新長度。
英文
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.
示例
["a","a","b","b","c","c","c"]
輸出:
返回6,輸入數組的前6個字符應該是:["a","2","b","2","c","3"]
說明:
"aa"被"a2"替代。"bb"被"b2"替代。"ccc"被"c3"替代。
提示
所有字符都有一個ASCII值在[35, 126]區間內。
1 <= len(chars) <= 1000。
進階
你能否僅使用O(1) 空間解決問題?
解題過程
- 解題過程不難思考,可是怎麼原地修改數組。。看了題解,發現大家採用的是雙指針策略,下面的代碼來自於題解。
class Solution {
public int compress(char[] chars) {
int s = 0;
int e = 0; //設置兩個指針,s:未壓縮字符串開頭,e:已壓縮的末尾
while(s < chars.length && e < chars.length){
chars[e++] = chars[s]; //這句話是要將非重複的字符記錄下來
int temp = s; //記錄下開始位置
while(s < chars.length && chars[e - 1] == chars[s]){
//判斷如果下一個字符和首字符相同
s++;
}
if(s - temp > 1){
//如果相同字符大於1
char[] flag = String.valueOf(s - temp).toCharArray();
for(char x: flag){
chars[e++] = x;
}
}
}
return e;
}
}
這道簡單題讓我有點受挫。。。。關於怎麼原地修改數組,還需要在看一下。
補下python代碼
class Solution:
def compress(self, chars: List[str]) -> int:
s = 0
e = 0
while s < len(chars) and e < len(chars):
chars[e] = chars[s] # 記錄非重複字符
temp = s
e += 1
while s < len(chars) and chars[e-1] == chars[s]: # 如果s 等於e - 1,說明重複
s += 1 # 繼續往下搜索
if s - temp > 1: # 如果長度大於1,則需要將e+1後位置放入壓縮字符的長度
flat = list(str(s - temp))
for x in flat:
chars[e] = x
e += 1
return e