vladimirVenkov

ValidateEditorial

Jun 21st, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Solution {
  4.     public static void main(String[] args) {
  5.         Scanner in = new Scanner(System.in);
  6.  
  7.         int n = in.nextInt();
  8.         in.nextLine();
  9.  
  10.         for (int i = 0; i < n; i++) {
  11.             String s = in.nextLine();
  12.             System.out.println(
  13.                 checkValidString(s)
  14.                     ? "yes"
  15.                     : "no"
  16.             );
  17.         }
  18.     }
  19.  
  20.     public static boolean checkValidString(String s, int index, int count) {
  21.         if (count < 0) {
  22.             return false;
  23.         }
  24.  
  25.         for (int i = index; i < s.length(); i++) {
  26.             if (s.charAt(i) == '(') {
  27.                 ++count;
  28.             } else if (s.charAt(i) == ')') {
  29.                 --count;
  30.                 if (count < 0) {
  31.                     return false;
  32.                 }
  33.             } else {
  34.                 return checkValidString(s, i + 1, count) ||
  35.                     checkValidString(s, i + 1, count + 1) ||
  36.                     checkValidString(s, i + 1, count - 1);
  37.             }
  38.         }
  39.  
  40.         return count == 0;
  41.     }
  42.  
  43.     public static boolean checkValidString(String s) {
  44.         return checkValidString(s, 0, 0);
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment