Skip to main content

rustgym/leetcode/
_443_string_compression.rs

1struct Solution;
2
3impl Solution {
4    fn compress(chars: &mut Vec<char>) -> i32 {
5        let mut j: usize = 0;
6        let mut prev: Option<char> = None;
7        let mut count = 0;
8        let n = chars.len();
9        for i in 0..n {
10            if let Some(c) = prev {
11                if c == chars[i] {
12                    count += 1;
13                } else {
14                    j += Self::write_pair(chars, j, c, count);
15                    prev = Some(chars[i]);
16                    count = 1;
17                }
18            } else {
19                count = 1;
20                prev = Some(chars[i]);
21            }
22        }
23        if let Some(c) = prev {
24            j += Self::write_pair(chars, j, c, count);
25        }
26        j as i32
27    }
28
29    fn write_pair(chars: &mut Vec<char>, mut index: usize, c: char, mut count: usize) -> usize {
30        chars[index] = c;
31        index += 1;
32        if count == 1 {
33            return 1;
34        }
35        let mut size: usize = 0;
36        while count > 0 {
37            let d: u8 = count as u8 % 10u8 + b'0';
38            chars[index + size] = d as char;
39            size += 1;
40            count /= 10;
41        }
42        let mut i = index;
43        let mut j = index + size - 1;
44        while i < j {
45            chars.swap(i, j);
46            i += 1;
47            j -= 1;
48        }
49        1 + size
50    }
51}
52
53#[test]
54fn test() {
55    let mut input: Vec<char> = [
56        "a", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b",
57    ]
58    .iter()
59    .map(|s| s.chars().next().unwrap())
60    .collect();
61    assert_eq!(Solution::compress(&mut input), 4);
62}