判断一个字符串 是否是 "等括号"字符串
- 等括号的含义
- 1).必须成对出现 有开始有结束 “()” “[]”
- 2).允许括号嵌套 “([])” “[{}([])]”
- 3).但是不允许单独嵌套 “{(})” “({[}])”
- 4).字符串中只有一共四种括号 () [] {} <>
- 题目: 要用户输入一个只包含这四种括号的字符串,判断该字符串是否是"等括号"字符串
思路:我们可以使用String类提供的replace静态方法
public class Demo {
public static void main(String[] args) {
System.out.println("输入一个字符串,判断是否为等括号字符串");
String s = new Scanner(System.in).nextLine();
while (s.length() != 0) {
int start = s.length();
//相邻就消除
s = s.replace("<>", "");
s = s.replace("[]", "");
s = s.replace("()", "");
s = s.replace("{}", "");
int end = s.length();
//如果长度不变则没进行过替换,则不是等括号字符串
if (end == start) {
System.out.println("不是等括号字符串.");
return;
}
}
System.out.println("是等括号字符串");
}
}