Skip to content

Commit 2e38730

Browse files
author
dai
committed
string add Bracket matching problem
1 parent a81a67f commit 2e38730

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

27-算法面试专题-字符串.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,5 +134,41 @@ public class StringUtil {
134134
}
135135
return true;
136136
}
137+
138+
139+
/**
140+
* 5、括号字符匹配问题:输入一个字符串,包含'(','[','{',')',']','}'几种括号,求是否是括号匹配的结果。
141+
* @param s
142+
* @return
143+
*/
144+
public static boolean isValid(String s) {
145+
146+
if (s == null || s.length() == 0) {
147+
return true;
148+
}
149+
150+
char[] str = s.toCharArray();
151+
Stack<Character> stack = new Stack<>();
152+
153+
for (int i = 0; i < str.length; i++) {
154+
char cha = str[i];
155+
// 遇到左括号,添加相应的右括号
156+
if (cha == '(' || cha == '[' || cha == '{') {
157+
stack.add(cha == '(' ? ')' : (cha == '[' ? ']' : '}'));
158+
} else { // 遇到右括号,弹出栈,比对相等
159+
if (stack.isEmpty()) {
160+
return false;
161+
}
162+
char last = stack.pop();
163+
if (cha != last) {
164+
return false;
165+
}
166+
}
167+
}
168+
169+
// 遍历结束,栈刚好为空。满足匹配要求
170+
return stack.isEmpty();
171+
}
172+
137173
}
138174
```

0 commit comments

Comments
 (0)