/**
* 判断字符中是否包含 (){}[] 格式字符
* <p>
* 把字符放入堆中 然后判断堆中的字符是否存在对应的一半,注意需要处理 ( 空格) 情况
*
* @param s
* @return
*/
public static boolean isValid(String s) {
try {
Stack<Character> stack = new Stack<>();
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
switch (ch[i]) {
case '{':
stack.push(ch[i]);
break;
case '[':
stack.push(ch[i]);
break;
case '(':
stack.push(ch[i]);
break;
case '}':
if (stack.peek() == '{') {
stack.pop();
break;
}
case ']':
if (stack.peek() == '[') {
stack.pop();
break;
}
case ')':
if (stack.peek() == '(') {
stack.pop();
break;
}
default:
if (stack.isEmpty()) {
//如果是空字符那么 跳过 继续比较一下个
continue;
}
}
}
if (stack.isEmpty()) {
System.out.println(" isValid : true");
return true;
} else {
System.out.println("isValid: false");
return false;
}
} catch (Exception e) {
//如果try中内容出现异常 肯定是输入内容不规范 例如 :{}] 不前括号则会抛异常 (EmptyStackException)
System.out.println("输入内容不符合规范,请检查后重试,输入内容:" + s + " ,格式规范:{([])},()[]{}, 请确认括号位置是否对等");
System.out.println("isValid : false");
return false;
}
}
public static boolean valid(String s) {
if (s.contains("()") || s.contains("{}") || s.contains("[]")) {
s = s.replace("()", "").replace("{}", "").replace("[]", "");
return valid(s);
} else {
return "".equals(s);
}
}
public static boolean valid1(String s) {
s = s.trim();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char ci = s.charAt(i);
if ('(' == ci) {
stack.push(')');
} else if ('{' == ci) {
stack.push('}');
} else if ('[' == ci) {
stack.push(']');
} else if (stack.isEmpty() || ci != stack.pop()) {
System.out.println("valid1: false");
return false;
}
}
System.out.println("valid1:" + stack.empty());
return stack.empty();
}
public static void main(String[] args) {
while (true) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入字符内容");
String str = scanner.nextLine();
isValid(str);
valid1(str);
if ("exit".equals(str)) {
System.out.print("结束");
break;
}
}
}
判断字符中是否包含 (){}[] 格式字符
最新推荐文章于 2022-04-10 11:00:00 发布