|
| 1 | +// 2490. Circular Sentence |
| 2 | +// 🟢 Easy |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/circular-sentence/ |
| 5 | +// |
| 6 | +// Tags: String |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Save the first char in the input, then iterate over the chars in the input checking that |
| 11 | + /// the chars before and after blank spaces match, if any of them do not, return false, |
| 12 | + /// otherwise return first == last. |
| 13 | + /// |
| 14 | + /// Time complexity: O(n) - We may visit all chars in the input. |
| 15 | + /// Space complexity: O(1) - We store two chars and one bool. |
| 16 | + /// |
| 17 | + /// Runtime 0 ms Beats 100% |
| 18 | + /// Memory 2.16 MB Beats 50% |
| 19 | + pub fn is_circular_sentence(sentence: String) -> bool { |
| 20 | + let first = sentence.chars().next().expect("A first char"); |
| 21 | + let (mut last, mut after_blank) = (first, false); |
| 22 | + for c in sentence.chars() { |
| 23 | + match c { |
| 24 | + ' ' => after_blank = true, |
| 25 | + _ => { |
| 26 | + if after_blank && c != last { |
| 27 | + return false; |
| 28 | + } |
| 29 | + after_blank = false; |
| 30 | + last = c; |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + first == last |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +// Tests. |
| 39 | +fn main() { |
| 40 | + let tests = [ |
| 41 | + ("leetcode exercises sound delightful", true), |
| 42 | + ("eetcode", true), |
| 43 | + ("Leetcode is cool", false), |
| 44 | + ]; |
| 45 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 46 | + let mut success = 0; |
| 47 | + for (i, t) in tests.iter().enumerate() { |
| 48 | + let res = Solution::is_circular_sentence(t.0.to_owned()); |
| 49 | + if res == t.1 { |
| 50 | + success += 1; |
| 51 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 52 | + } else { |
| 53 | + println!( |
| 54 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 55 | + i, t.1, res |
| 56 | + ); |
| 57 | + } |
| 58 | + } |
| 59 | + println!(); |
| 60 | + if success == tests.len() { |
| 61 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 62 | + } else if success == 0 { |
| 63 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 64 | + } else { |
| 65 | + println!( |
| 66 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 67 | + tests.len() - success |
| 68 | + ) |
| 69 | + } |
| 70 | +} |
0 commit comments