File tree Expand file tree Collapse file tree 1 file changed +111
-0
lines changed
Expand file tree Collapse file tree 1 file changed +111
-0
lines changed Original file line number Diff line number Diff line change 1+ # 20、有效的括号
2+
3+ 给定一个只包括 '(',')','{','}','[ ','] ' 的字符串 s ,判断字符串是否有效。
4+
5+ 有效字符串需满足:
6+
7+ 左括号必须用相同类型的右括号闭合。
8+ 左括号必须以正确的顺序闭合。
9+
10+
11+ 示例 1:
12+
13+ ```
14+ 输入:s = "()"
15+ 输出:true
16+ ```
17+
18+
19+ 示例 2:
20+
21+ ```
22+ 输入:s = "()[]{}"
23+ 输出:true
24+ ```
25+
26+
27+ 示例 3:
28+
29+ ```
30+ 输入:s = "(]"
31+ 输出:false
32+ ```
33+
34+
35+ 示例 4:
36+
37+ ```
38+ 输入:s = "([)]"
39+ 输出:false
40+ ```
41+
42+
43+ 示例 5:
44+
45+ ```
46+ 输入:s = "{[]}"
47+ 输出:true
48+ ```
49+
50+
51+ 提示:
52+
53+ 1 <= s.length <= 104
54+ s 仅由括号 '()[ ] {}' 组成
55+
56+ 来源:力扣(LeetCode)
57+ 链接:https://leetcode-cn.com/problems/valid-parentheses
58+ 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
59+
60+ c语言实现
61+
62+ ``` c
63+ bool isValid (char * s){
64+ int n = strlen(s);
65+ char a[ n] ;
66+ int top = 0;
67+ a[ top] =s[ top] ;
68+ for(int i = 1;i<n;i++){
69+ top++;
70+ a[ top] =s[ i] ;
71+ if(top==0){continue;}
72+ else if(a[ top-1] =='('&&a[ top] ==')'||a[ top-1] =='[ '&&a[ top] =='] '||a[ top-1] =='{'&&a[ top] =='}'){
73+ top-=2;
74+ }
75+ }
76+ if(top==-1){
77+ return true;
78+ }else{
79+ return false;
80+ }
81+ }
82+ ```
83+
84+ java实现
85+
86+ ```java
87+ class Solution {
88+ public boolean isValid(String s) {
89+ char[] arr = s.toCharArray();
90+ int n = arr.length;
91+ char []a = new char[n];
92+ int top = 0;
93+ a[0] = arr[0];
94+ for(int i = 1;i<n;){
95+ top++;
96+ a[top]=arr[i];
97+ i++;
98+ if(top==0){continue;}
99+ else if(a[top-1]=='('&&a[top]==')'||a[top-1]=='['&&a[top]==']'||a[top-1]=='{'&&a[top]=='}'){
100+ top-=2;
101+ }
102+ }
103+ if(top==-1){
104+ return true;
105+ }else{
106+ return false;
107+ }
108+ }
109+ }
110+ ```
111+
You can’t perform that action at this time.
0 commit comments