Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 3afc6ad

Browse files
author
Zhang Xiaodong
committed
solve 32
1 parent efb166d commit 3afc6ad

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,4 @@ mod s0028_find_the_index_of_the_first_occurrence_in_a_string;
2727
mod s0029_divide_two_integers;
2828
mod s0030_substring_with_concatenation_of_all_words;
2929
mod s0031_next_permutation;
30+
mod s0032_longest_valid_parentheses;
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
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+
}

0 commit comments

Comments
 (0)