java实现括号匹配(附完整源码)
时间: 2023-11-11 13:03:24 浏览: 41
好的,下面是 Java 实现括号匹配的完整源码:
```java
import java.util.Stack;
public class BracketMatching {
public static void main(String[] args) {
String str1 = "((()))";
String str2 = "()()()";
String str3 = "((())";
String str4 = "(()))";
String str5 = "((())())";
System.out.println(str1 + " is " + (isMatched(str1) ? "matched" : "not matched"));
System.out.println(str2 + " is " + (isMatched(str2) ? "matched" : "not matched"));
System.out.println(str3 + " is " + (isMatched(str3) ? "matched" : "not matched"));
System.out.println(str4 + " is " + (isMatched(str4) ? "matched" : "not matched"));
System.out.println(str5 + " is " + (isMatched(str5) ? "matched" : "not matched"));
}
public static boolean isMatched(String str) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '(') {
stack.push(c);
} else if (c == ')') {
if (stack.isEmpty() || stack.pop() != '(') {
return false;
}
}
}
return stack.isEmpty();
}
}
```
上述代码中的 `isMatched` 方法接收一个字符串参数,利用栈来检查字符串中的括号是否匹配。具体来说,如果遇到左括号,就将其压入栈中;如果遇到右括号,就将栈顶元素弹出,如果弹出的不是左括号或者栈为空,就说明括号不匹配。最后,如果栈为空,说明括号全部匹配。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)