Skip to content

Commit 6a9b4a7

Browse files
committed
Leetcode 32
1 parent bc3f1f9 commit 6a9b4a7

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

0-50/32.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
## :pencil2:基础刷题之(32. Longest Valid Parentheses)
2+
3+
**2020-02-17 吴亲库里 库里的深夜食堂**
4+
5+
### :pencil2:题目描述
6+
7+
**给定一个只有 '(' 和 ')' 的字符串,让我们找出最长的有效括号,题目给了两个实例。 **
8+
9+
### :pencil2:题目实例
10+
<a href="https://github.com/wuqinqiang/">
11+
​ <img src="https://github.com/wuqinqiang/Lettcode-php/blob/master/images/32.png">
12+
</a>
13+
14+
****
15+
16+
### :pencil2:题目分析
17+
**涉及到这些括号匹配都可以使用到栈。核心就是对于 '(' 符号,将此时遍历的下标直接入栈,对于 ')',我们弹出栈顶元素,并将当前遍历的下标和栈顶元素下标求差,得出当前位置最长有效括号数。在开头位置直接先入栈一个 -1,可以自己动手试试为什么。**
18+
****
19+
20+
### :pencil2:最终实现代码
21+
22+
```php
23+
/**
24+
* @param String $s
25+
* @return Integer
26+
*/
27+
function longestValidParentheses($s) {
28+
$stack=[];
29+
$max=0;
30+
array_unshift($stack,-1);
31+
for($i=0;$i<strlen($s);$i++){
32+
if($s[$i]=='('){
33+
array_unshift($stack,$i);
34+
}else{
35+
array_shift($stack);
36+
if(empty($stack)){
37+
array_unshift($stack,$i);
38+
}else{
39+
$max=max($max,$i-$stack[0]);
40+
}
41+
}
42+
}
43+
return $max;
44+
}
45+
46+
```
47+
****
48+
49+
### 联系
50+
51+
<a href="https://github.com/wuqinqiang/">
52+
​ <img src="https://github.com/wuqinqiang/Lettcode-php/blob/master/qrcode_for_gh_c194f9d4cdb1_430.jpg" width="150px" height="150px">
53+
</a>

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
- [Leetcode24](https://github.com/wuqinqiang/Lettcode-php/blob/master/0-50/24.md)
5454
- [Leetcode25](https://github.com/wuqinqiang/Lettcode-php/blob/master/0-50/25.md)
5555
- [Leetcode31](https://github.com/wuqinqiang/Lettcode-php/blob/master/0-50/31.md)
56+
- [Leetcode32](https://github.com/wuqinqiang/Lettcode-php/blob/master/0-50/32.md)
5657
- [Leetcode33](https://github.com/wuqinqiang/Lettcode-php/blob/master/0-50/33.md)
5758
- [Leetcode34](https://github.com/wuqinqiang/Lettcode-php/blob/master/0-50/34.md)
5859
- [Leetcode35](https://github.com/wuqinqiang/Lettcode-php/blob/master/0-50/35.md)

0 commit comments

Comments
 (0)