|
| 1 | +// 1957. Delete Characters to Make Fancy String |
| 2 | +// 🟢 Easy |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/delete-characters-to-make-fancy-string/ |
| 5 | +// |
| 6 | +// Tags: String |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Iterate over the input counting the frequency of characters, append to the result string |
| 11 | + /// while the current character is repeated a maximum of 2 times. |
| 12 | + /// |
| 13 | + /// Time complexity: O(n) |
| 14 | + /// Space complexity: O(n) |
| 15 | + /// |
| 16 | + /// Runtime 2 ms Beats 100% |
| 17 | + /// Memory 2.51 MB Beats 28.57% |
| 18 | + pub fn make_fancy_string(s: String) -> String { |
| 19 | + let mut res = String::with_capacity(s.len()); |
| 20 | + let mut last = '?'; |
| 21 | + let mut repeated = false; |
| 22 | + for c in s.chars() { |
| 23 | + if c == last { |
| 24 | + if repeated { |
| 25 | + continue; |
| 26 | + } |
| 27 | + repeated = true; |
| 28 | + } else { |
| 29 | + last = c; |
| 30 | + repeated = false; |
| 31 | + } |
| 32 | + res.push(c); |
| 33 | + } |
| 34 | + res |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +// Tests. |
| 39 | +fn main() { |
| 40 | + let tests = [("leeetcode", "leetcode"), ("aaabaaaa", "aabaa")]; |
| 41 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 42 | + let mut success = 0; |
| 43 | + for (i, t) in tests.iter().enumerate() { |
| 44 | + let res = Solution::make_fancy_string(t.0.to_string()); |
| 45 | + if res == t.1 { |
| 46 | + success += 1; |
| 47 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 48 | + } else { |
| 49 | + println!( |
| 50 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 51 | + i, t.1, res |
| 52 | + ); |
| 53 | + } |
| 54 | + } |
| 55 | + println!(); |
| 56 | + if success == tests.len() { |
| 57 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 58 | + } else if success == 0 { |
| 59 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 60 | + } else { |
| 61 | + println!( |
| 62 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 63 | + tests.len() - success |
| 64 | + ) |
| 65 | + } |
| 66 | +} |
0 commit comments