File tree 2 files changed +84
-0
lines changed 2 files changed +84
-0
lines changed Original file line number Diff line number Diff line change @@ -27,3 +27,4 @@ mod s0028_find_the_index_of_the_first_occurrence_in_a_string;
27
27
mod s0029_divide_two_integers;
28
28
mod s0030_substring_with_concatenation_of_all_words;
29
29
mod s0031_next_permutation;
30
+ mod s0032_longest_valid_parentheses;
Original file line number Diff line number Diff line change
1
+ use std:: thread:: current;
2
+
3
+ /**
4
+ * [32] 最长有效括号
5
+ *
6
+ * 给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
7
+ *
8
+ * <div class="original__bRMd">
9
+ * <div>
10
+ * 示例 1:
11
+ *
12
+ * 输入:s = "(()"
13
+ * 输出:2
14
+ * 解释:最长有效括号子串是 "()"
15
+ *
16
+ * 示例 2:
17
+ *
18
+ * 输入:s = ")()())"
19
+ * 输出:4
20
+ * 解释:最长有效括号子串是 "()()"
21
+ *
22
+ * 示例 3:
23
+ *
24
+ * 输入:s = ""
25
+ * 输出:0
26
+ *
27
+ *
28
+ * 提示:
29
+ *
30
+ * 0 <= s.length <= 3 * 10^4
31
+ * s[i] 为 '(' 或 ')'
32
+ * </div>
33
+ * </div>
34
+ *
35
+ */
36
+ pub struct Solution { }
37
+
38
+ // problem: https://leetcode.cn/problems/longest-valid-parentheses/
39
+ // discuss: https://leetcode.cn/problems/longest-valid-parentheses/discuss/?currentPage=1&orderBy=most_votes&query=
40
+
41
+ // submission codes start here
42
+
43
+ impl Solution {
44
+ pub fn longest_valid_parentheses ( s : String ) -> i32 {
45
+ let mut parenthesses = vec ! [ ] ;
46
+ let mut max_num = 0 ;
47
+ let mut cur_num = 0 ;
48
+ for b in s. as_bytes ( ) {
49
+ if * b == b'(' {
50
+ parenthesses. push ( b) ;
51
+ continue ;
52
+ }
53
+ if parenthesses. len ( ) == 0 {
54
+ if cur_num > max_num {
55
+ max_num = cur_num;
56
+ }
57
+ cur_num = 0 ;
58
+ parenthesses. clear ( ) ;
59
+ continue ;
60
+ }
61
+ parenthesses. pop ( ) ;
62
+ cur_num += 1 ;
63
+ }
64
+ if cur_num > max_num {
65
+ max_num = cur_num;
66
+ }
67
+ max_num << 1
68
+ }
69
+ }
70
+
71
+ // submission codes end
72
+
73
+ #[ cfg( test) ]
74
+ mod tests {
75
+ use super :: * ;
76
+
77
+ #[ test]
78
+ fn test_32 ( ) {
79
+ assert_eq ! ( Solution :: longest_valid_parentheses( "(()" . to_string( ) ) , 2 ) ;
80
+ assert_eq ! ( Solution :: longest_valid_parentheses( ")()())" . to_string( ) ) , 4 ) ;
81
+ assert_eq ! ( Solution :: longest_valid_parentheses( "" . to_string( ) ) , 0 ) ;
82
+ }
83
+ }
You can’t perform that action at this time.
0 commit comments