443. String Compression
use hashmap
T: O(n)
S: O(n)
use two pointers
T: O(n),
S: O(1)
class Solution {
public int compress(char[] chars) {
int n = chars.length;
int newIdx = 0;
int right = 0; // ็ถๅ
ธ็ๅๅ้ๆ้
int left = 0;
while (right < n) {
char c = chars[left];
while (right < n && chars[left] == chars[right]) {
right++;
}
int freq = right - left;
// 1. append this letter
chars[newIdx++] = c;
// 2. if count != 1, need append count char (12 => "1", "2")
if (freq != 1) {
for (char countChar : String.valueOf(freq).toCharArray()) {
chars[newIdx++] = countChar;
}
}
left = right;
}
return newIdx; // newIdx, at last will be the length (newIdx++ one more time)
}
}
/*
If the group's length is 1, append the character to s.
Otherwise, append the character followed by the group's length.
abb
ab2
Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
ab12
solution: T: O(n), S: O(1)
use two pointers to get freq count
this q, chars also needs modifying:
After you are done modifying the input array, return the new length of the array.
["a","a","b","b","c","c","c"]
i. j
i
1. append this letter
2. if count != 1, need append count char (12 => "1", "2")
*/
็ฑปไผผไธไธๅ๏ผไฝ่ฆๆฑ in place๏ผ้ฟๅบฆไธบ1ไน่ฎฐๅฝ่ฟๅป๏ผๅฆๆๅ็ผฉๅ้ฟๅบฆๅคงไบๅๅญ็ฌฆไธฒ๏ผ่ฟๅerrorใ
ๅฝๅบ็ดงๅผ ่ฟ็นๆฒกๆณๆ็ฝๆไนๅใ
ๆฏๅฆ
"aaa" -> "3a"๏ผ่ฝๅ็ผฉ
"abc" -> "1a1b1c", ไธ่ฝๅ็ผฉ
"abbb" -> "a1b3", ่ฝๅ็ผฉ
class Solution {
public int compress(char[] chars) {
int n = chars.length;
int newIdx = 0;
int right = 0; // ็ถๅ
ธ็ๅๅ้ๆ้
int left = 0;
while (right < n) {
char c = chars[left];
while (right < n && chars[left] == chars[right]) {
right++;
}
int freq = right - left;
try {
// 1. append this letter
chars[newIdx++] = c;
// 2. append count
for (char countChar : String.valueOf(freq).toCharArray()) {
chars[newIdx++] = countChar;
}
} catch (Exception e) {
throw new RuntimeException("illegal compressed");
}
left = right;
}
return newIdx; // newIdx, at last will be the length (newIdx++ one more time)
}
}
Previouslintcode 1375 ยท Substring With At Least K Distinct CharactersNext1855. Maximum Distance Between a Pair of Values
Last updated