从键盘输入一个包含有花括号、中括号、小括号的字符串判断括号是否正确匹配输出判断结果。用java方法编写
可以使用栈的数据结构来解决这个问题。具体的步骤如下:
- 创建一个空栈。
- 遍历输入的字符串中的每一个字符。
- 如果字符是左括号(包括{、[、(),则将其压入栈中。
- 如果字符是右括号(包括}、]、)),则检查栈顶元素是否与该右括号匹配。如果匹配,则将栈顶元素弹出栈;如果不匹配,则返回false。
- 遍历完所有字符后,检查栈是否为空。如果为空,则返回true;如果不为空,则返回false。
下面是使用Java代码实现上述算法的示例:
import java.util.Stack;
public class BracketMatching {
public static boolean isBracketMatching(String str) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '{' || c == '[' || c == '(') {
stack.push(c);
} else if (c == '}' || c == ']' || c == ')') {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if ((c == '}' && top != '{') ||
(c == ']' && top != '[') ||
(c == ')' && top != '(')) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
String str = "{[()]}";
boolean result = isBracketMatching(str);
System.out.println(result); // 输出true
str = "{[(])}";
result = isBracketMatching(str);
System.out.println(result); // 输出false
}
}
在上述示例中,我们定义了一个isBracketMatching方法来判断括号是否正确匹配。在main方法中,我们分别测试了一个正确匹配的字符串和一个不正确匹配的字符串。程序会依次输出true和false
原文地址: https://www.cveoy.top/t/topic/hG5A 著作权归作者所有。请勿转载和采集!