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)
    }
}

Last updated