File tree 2 files changed +86
-0
lines changed
2 files changed +86
-0
lines changed Original file line number Diff line number Diff line change @@ -15,3 +15,4 @@ mod s0016_3sum_closest;
15
15
mod s0017_letter_combinations_of_a_phone_number;
16
16
mod s0018_4sum;
17
17
mod s0019_remove_nth_node_from_end_of_list;
18
+ mod s0020_valid_parentheses;
Original file line number Diff line number Diff line change
1
+ /**
2
+ * [20] 有效的括号
3
+ *
4
+ * 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
5
+ * 有效字符串需满足:
6
+ * <ol>
7
+ * 左括号必须用相同类型的右括号闭合。
8
+ * 左括号必须以正确的顺序闭合。
9
+ * 每个右括号都有一个对应的相同类型的左括号。
10
+ * </ol>
11
+ *
12
+ * 示例 1:
13
+ *
14
+ * 输入:s = "()"
15
+ * 输出:true
16
+ *
17
+ * 示例 2:
18
+ *
19
+ * 输入:s = "()[]{}"
20
+ * 输出:true
21
+ *
22
+ * 示例 3:
23
+ *
24
+ * 输入:s = "(]"
25
+ * 输出:false
26
+ *
27
+ *
28
+ * 提示:
29
+ *
30
+ * 1 <= s.length <= 10^4
31
+ * s 仅由括号 '()[]{}' 组成
32
+ *
33
+ */
34
+ pub struct Solution { }
35
+
36
+ // problem: https://leetcode.cn/problems/valid-parentheses/
37
+ // discuss: https://leetcode.cn/problems/valid-parentheses/discuss/?currentPage=1&orderBy=most_votes&query=
38
+
39
+ // submission codes start here
40
+
41
+ impl Solution {
42
+ pub fn is_valid ( s : String ) -> bool {
43
+ let mut brackets = vec ! [ ] ;
44
+ for c in s. as_bytes ( ) {
45
+ match c {
46
+ b'(' | b'[' | b'{' => {
47
+ brackets. push ( * c) ;
48
+ } ,
49
+ b')' | b']' | b'}' => {
50
+ if brackets. last ( ) . is_none ( ) {
51
+ return false ;
52
+ }
53
+ let t = brackets. pop ( ) . unwrap ( ) ;
54
+ if * c == b')' && t != b'(' {
55
+ return false ;
56
+ } else if * c == b']' && t != b'[' {
57
+ return false ;
58
+ } else if * c == b'}' && t != b'{' {
59
+ return false ;
60
+ }
61
+
62
+ } ,
63
+ _ => { } ,
64
+ }
65
+ }
66
+ brackets. is_empty ( )
67
+ }
68
+ }
69
+
70
+ // submission codes end
71
+
72
+ #[ cfg( test) ]
73
+ mod tests {
74
+ use super :: * ;
75
+
76
+ #[ test]
77
+ fn test_20 ( ) {
78
+ assert_eq ! ( Solution :: is_valid( "[" . to_string( ) ) , false ) ;
79
+ assert_eq ! ( Solution :: is_valid( "]]]" . to_string( ) ) , false ) ;
80
+ assert_eq ! ( Solution :: is_valid( "[sdfs]" . to_string( ) ) , true ) ;
81
+ assert_eq ! ( Solution :: is_valid( "[]" . to_string( ) ) , true ) ;
82
+ assert_eq ! ( Solution :: is_valid( "()[]{}" . to_string( ) ) , true ) ;
83
+ assert_eq ! ( Solution :: is_valid( "[)" . to_string( ) ) , false ) ;
84
+ }
85
+ }
You can’t perform that action at this time.
0 commit comments