STANAANDREY

rust 1337code template

Sep 10th, 2025
980
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.42 KB | None | 0 0
  1.  
  2. struct Solution {}
  3. impl Solution {
  4.     pub fn is_valid(s: String) -> bool {
  5.         let mut stack: Vec<char> = Vec::new();
  6.  
  7.         for ch in s.chars() {
  8.             match ch {
  9.                 ')' => {
  10.                     if stack.is_empty() || stack.pop().unwrap() != '(' {
  11.                         return false;
  12.                     }
  13.                 },
  14.                 ']' => {
  15.                     if stack.is_empty() || stack.pop().unwrap() != '[' {
  16.                         return false;
  17.                     }
  18.                 },
  19.                 '}' => {
  20.                     if stack.is_empty() || stack.pop().unwrap() != '{' {
  21.                         return false;
  22.                     }
  23.                 },
  24.                 _ => stack.push(ch),
  25.             }
  26.         }
  27.  
  28.         stack.is_empty()
  29.     }
  30. }
  31.  
  32. fn main() {
  33.     // Test cases
  34.     let test_cases = vec![
  35.         ("()", true),
  36.         ("()[]{}", true),
  37.         ("(]", false),
  38.         ("([)]", false),
  39.         ("{[]}", true),
  40.         ("", true),
  41.         ("[", false),
  42.         ("]", false),
  43.     ];
  44.  
  45.     for (i, (input, expected)) in test_cases.iter().enumerate() {
  46.         let result = Solution::is_valid(input.to_string());
  47.         println!("Test {}: '{}' -> {} (expected: {})",
  48.                  i + 1, input, result, expected);
  49.         assert_eq!(result, *expected, "Test failed for input: '{}'", input);
  50.     }
  51.  
  52.     println!("All tests passed!");
  53. }
Advertisement
Add Comment
Please, Sign In to add comment