Given a string word, compress it using the following algorithm:
Begin with an empty string comp. While word is not empty, use the following operation:
Remove a maximum length prefix of word made of a single character c repeating at most 9 times.
Append the length of the prefix followed by c to comp.
Return the string comp.
Example 1:
Input: word = "abcde"
Output: "1a1b1c1d1e"
Explanation:
Initially, comp = "". Apply the operation 5 times, choosing "a", "b", "c", "d", and "e" as the prefix in each operation.
For each prefix, append "1" followed by the character to comp.
Example 2:
Input: word = "aaaaaaaaaaaaaabb"
Output: "9a5a2b"
Explanation:
Initially, comp = "". Apply the operation 3 times, choosing "aaaaaaaaa", "aaaaa", and "bb" as the prefix in each operation.
For prefix "aaaaaaaaa", append "9" followed by "a" to comp.
For prefix "aaaaa", append "5" followed by "a" to comp.
For prefix "bb", append "2" followed by "b" to comp.
Constraints:
1 <= word.length <= 2 * 105
word consists only of lowercase English letters.
壓縮字串 III。
給你一個字串 word,請你使用以下演算法進行壓縮: - 從空字串 comp 開始。當 word 不為空 時,執行以下操作: - 移除 word 的最長單字元字首,該字首由單一字元 c 重複多次組成,且該字首長度 最多 為 9 。 - 將字首的長度和字元 c 追加到 comp 。 返回字串 comp 。
思路
這是一道模擬題。按照題意卡住條件即可,可直接參見程式碼。
複雜度
時間O(n)
空間O(n) - output 也是個字串
程式碼
Java實現
class Solution {
public String compressedString(String word) {
StringBuilder sb = new StringBuilder();
int n = word.length();
int i = 0;
int count = 0;
while (i < n) {
char cur = word.charAt(i);
while (i < n && word.charAt(i) == cur && count < 9) {
count++;
i++;
}
sb.append(count);
sb.append(cur);
count = 0;
}
return sb.toString();
}
}