Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Solution {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int n = in.nextInt();
- in.nextLine();
- for (int i = 0; i < n; i++) {
- String s = in.nextLine();
- System.out.println(
- checkValidString(s)
- ? "yes"
- : "no"
- );
- }
- }
- public static boolean checkValidString(String s, int index, int count) {
- if (count < 0) {
- return false;
- }
- for (int i = index; i < s.length(); i++) {
- if (s.charAt(i) == '(') {
- ++count;
- } else if (s.charAt(i) == ')') {
- --count;
- if (count < 0) {
- return false;
- }
- } else {
- return checkValidString(s, i + 1, count) ||
- checkValidString(s, i + 1, count + 1) ||
- checkValidString(s, i + 1, count - 1);
- }
- }
- return count == 0;
- }
- public static boolean checkValidString(String s) {
- return checkValidString(s, 0, 0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment