Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct Solution {}
- impl Solution {
- pub fn is_valid(s: String) -> bool {
- let mut stack: Vec<char> = Vec::new();
- for ch in s.chars() {
- match ch {
- ')' => {
- if stack.is_empty() || stack.pop().unwrap() != '(' {
- return false;
- }
- },
- ']' => {
- if stack.is_empty() || stack.pop().unwrap() != '[' {
- return false;
- }
- },
- '}' => {
- if stack.is_empty() || stack.pop().unwrap() != '{' {
- return false;
- }
- },
- _ => stack.push(ch),
- }
- }
- stack.is_empty()
- }
- }
- fn main() {
- // Test cases
- let test_cases = vec![
- ("()", true),
- ("()[]{}", true),
- ("(]", false),
- ("([)]", false),
- ("{[]}", true),
- ("", true),
- ("[", false),
- ("]", false),
- ];
- for (i, (input, expected)) in test_cases.iter().enumerate() {
- let result = Solution::is_valid(input.to_string());
- println!("Test {}: '{}' -> {} (expected: {})",
- i + 1, input, result, expected);
- assert_eq!(result, *expected, "Test failed for input: '{}'", input);
- }
- println!("All tests passed!");
- }
Advertisement
Add Comment
Please, Sign In to add comment