Skip to content

Instantly share code, notes, and snippets.

@shubhamkumar13
Created October 23, 2020 03:43
Show Gist options
  • Save shubhamkumar13/57ef95b245d99aa6eeee19e1bb4a16ac to your computer and use it in GitHub Desktop.
Save shubhamkumar13/57ef95b245d99aa6eeee19e1bb4a16ac to your computer and use it in GitHub Desktop.
Leetcode - Valid Parenthesis
// Problem link -> https://leetcode.com/problems/valid-parentheses/
fn main() {
assert_eq!(Solution::is_valid("()".to_string()), true);
assert_eq!(Solution::is_valid("()[]{}".to_string()), true);
assert_eq!(Solution::is_valid("(]".to_string()), false);
assert_eq!(Solution::is_valid("([)]".to_string()), false);
assert_eq!(Solution::is_valid("{[]}".to_string()), true);
assert_eq!(Solution::is_valid("]".to_string()), false);
}
enum Solution {}
use std::collections::{VecDeque, HashMap};
impl Solution {
pub fn is_valid(s: String) -> bool {
let mut sv : Vec<char> = s.chars().collect();
let mut stack = VecDeque::new();
let mut map = HashMap::new();
map.insert(')','(');
map.insert(']','[');
map.insert('}','{');
let mut flag = true;
let mut counter = 0;
for c in sv.into_iter() {
match c {
'(' | '[' | '{' => {stack.push_front(c); counter += 1;},
')' | ']' | '}' => {
if let Some(x) = stack.pop_front() {
if let Some (&ch) = map.get(&c) {
if ch != x {
flag = false;
break;
} else {
counter -= 1;
}
} else {
panic!("This is not part of the bracket map");
}
} else {
flag = false;
counter = -1;
break;
}
},
_ => panic!("This is not a bracket"),
}
}
if counter == 0 {
flag = true;
} else {
flag = false;
}
flag
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment