|
| 1 | +// 2000. Reverse Prefix of Word |
| 2 | +// 🟢 Easy |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/reverse-prefix-of-word/ |
| 5 | +// |
| 6 | +// Tags: Two Pointers - String |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Check if the character is found in the input, if found reverse the characters up to and |
| 11 | + /// including that index, then append the remaining characters and return that. |
| 12 | + /// |
| 13 | + /// Time complexity: O(n) - We iterate over the characters once to find the first index of, if |
| 14 | + /// found, we iterate in reverse over the characters up to that index then forward over the |
| 15 | + /// characters after that index, building the result. |
| 16 | + /// Space complexity: O(1) - Unless iterators are internally using extra memory, which I don't |
| 17 | + /// think is the case, then constant extra memory. |
| 18 | + /// |
| 19 | + /// Runtime 0 ms Beats 100% |
| 20 | + /// Memory 2.07 MB Beats 90% |
| 21 | + pub fn reverse_prefix(word: String, ch: char) -> String { |
| 22 | + match word.chars().position(|c| c == ch) { |
| 23 | + Some(i) => word[..=i] |
| 24 | + .chars() |
| 25 | + .rev() |
| 26 | + .chain(word[i + 1..].chars()) |
| 27 | + .collect(), |
| 28 | + None => word, |
| 29 | + } |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +// Tests. |
| 34 | +fn main() { |
| 35 | + let tests = [ |
| 36 | + ("abcdefd", 'd', "dcbaefd"), |
| 37 | + ("xyxzxe", 'z', "zxyxxe"), |
| 38 | + ("abcd", 'z', "abcd"), |
| 39 | + ]; |
| 40 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 41 | + let mut success = 0; |
| 42 | + for (i, t) in tests.iter().enumerate() { |
| 43 | + let res = Solution::reverse_prefix(t.0.to_string(), t.1); |
| 44 | + if res == t.2 { |
| 45 | + success += 1; |
| 46 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 47 | + } else { |
| 48 | + println!( |
| 49 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 50 | + i, t.2, res |
| 51 | + ); |
| 52 | + } |
| 53 | + } |
| 54 | + println!(); |
| 55 | + if success == tests.len() { |
| 56 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 57 | + } else if success == 0 { |
| 58 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 59 | + } else { |
| 60 | + println!( |
| 61 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 62 | + tests.len() - success |
| 63 | + ) |
| 64 | + } |
| 65 | +} |
0 commit comments