leetcode/
longest_valid_parentheses.rs1use std::cmp::max;
27
28pub struct Solution;
38
39impl Solution {
40
41 pub fn longest_valid_parentheses(s: String) -> i32 {
42 let from_left = longest(s.chars());
43 let from_right = longest(s.chars().rev().map(|c| match c {
44 '(' => ')',
45 ')' => '(',
46 _ => unreachable!(),
47 }));
48 max(from_left, from_right) as i32
49 }
50}
51
52fn longest<T: Iterator<Item = char>>(chars: T) -> u32 {
53 chars.fold((0, 0, 0), |(longest, left, right), c| match c {
54 '(' => (longest, left + 1, right),
55 ')' if left == right + 1 => (max(longest, left * 2), left, right + 1),
56 ')' if left > right => (longest, left, right + 1),
57 ')' => (longest, 0, 0),
58 _ => unreachable!(),
59 }).0
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65
66 #[test]
67 fn test() {
68 let cases = vec![
69 (2, "(()(((()"),
70 (4, ")()())"),
71 (4, "(()()"),
72 (6, "((((()))"),
73 (0, ""),
74 (0, "(((("),
75 (0, ")(("),
76 (0, ")))"),
77 (0, ")))("),
78 (2, "()(()"),
79 (2, "(()"),
80 (4, ")()())"),
81 (18, "(((((())))()()()))"),
82 (18, "(()))))))(())))(((((())))()()()))"),
83 ];
84
85 for (expect, s) in cases {
86 assert_eq!(expect, Solution::longest_valid_parentheses(s.into()));
87 }
88 }
89}