给定一个字符串str,判断是不是整体有效的括号字符串(整体有效:即存在一种括号匹配方案,使每个括号字符均能找到对应的反向括号,且字符串中不包含非括号字符)。
数据范围:
输入包含一行,代表str。
输出一行,如果str是整体有效的括号字符串,请输出“YES”,否则输出“NO”。
(())
YES
()a()
NO
()a()中包含了 ‘a’,a不是括号字符
时间复杂度,额外空间复杂度
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); System.out.println(check(s) ? "YES": "NO"); } private static boolean check(String s) { if (s == null || s.length() == 0) return false; int count = 0; for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == '(') { count++; } else if (s.charAt(i) == ')'){ if (--count < 0) { return false; } } else { return false; } } return count == 0; } }
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String input = sc.nextLine(); boolean res = validBracket(input); if (res) { System.out.println("YES"); } else { System.out.println("NO"); } } } public static boolean validBracket(String input) { // Corner case if (input == null || input.length() == 0) { return true; } if (input.length() % 2 != 0) { return false; } char[] array = input.toCharArray(); // Use a stack LinkedList<Character> stack = new LinkedList<>(); for (int i = 0; i < array.length; i++) { if (array[i] == '(') { stack.push(array[i]); } else if (array[i] == ')') { if (!stack.isEmpty() && stack.peek() == '(') { stack.pop(); } else { return false; } } else { return false; } } // Post Processing return stack.isEmpty(); } }