20. Valid Parentheses Easy
1/**
2 * [20] Valid Parentheses
3 *
4 * Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
5 * An input string is valid if:
6 * <ol>
7 * Open brackets must be closed by the same type of brackets.
8 * Open brackets must be closed in the correct order.
9 * </ol>
10 *
11 * Example 1:
12 *
13 * Input: s = "()"
14 * Output: true
15 *
16 * Example 2:
17 *
18 * Input: s = "()[]{}"
19 * Output: true
20 *
21 * Example 3:
22 *
23 * Input: s = "(]"
24 * Output: false
25 *
26 *
27 * Constraints:
28 *
29 * 1 <= s.length <= 10^4
30 * s consists of parentheses only '()[]{}'.
31 *
32 */
33pub struct Solution {}
34
35// problem: https://leetcode.com/problems/valid-parentheses/
36// discuss: https://leetcode.com/problems/valid-parentheses/discuss/?currentPage=1&orderBy=most_votes&query=
37
38// submission codes start here
39
40impl Solution {
41 pub fn is_valid(s: String) -> bool {
42 let mut v: Vec<char> = vec![];
43 for c in s.chars() {
44 if c == '(' {
45 v.push(')');
46 } else if c == '[' {
47 v.push(']');
48 } else if c == '{' {
49 v.push('}');
50 } else if v.is_empty() || v.pop().unwrap() != c {
51 return false;
52 }
53 }
54 v.is_empty()
55 }
56}
57
58// submission codes end
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63
64 #[test]
65 fn test_20() {
66 assert_eq!(Solution::is_valid("()[]{}".to_string()), true);
67 assert_eq!(Solution::is_valid("()[]{}{".to_string()), false);
68 assert_eq!(Solution::is_valid("([)]{}".to_string()), false);
69 }
70}
71
Back
© 2025 bowen.ge All Rights Reserved.