Tranvick

Laba

Oct 2nd, 2013
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3.  
  4. public class Main {
  5.  
  6.     private static String work(String s) {
  7.         int max = 0, cnt = 0, beg = -1;
  8.         for (int i = 0; i < s.length(); ++i) {
  9.             if (s.charAt(i) == '(') {
  10.                 ++cnt;
  11.             } else if (s.charAt(i) == ')') {
  12.                 --cnt;
  13.             }
  14.             if (cnt > max) {
  15.                 max = cnt;
  16.             }
  17.         }
  18.         cnt = 0;
  19.         for (int i = 0; i < s.length(); ++i) {
  20.             if (s.charAt(i) == '(') {
  21.                 beg = i;
  22.                 ++cnt;
  23.             }
  24.             if (s.charAt(i) == ')') {
  25.                 if (cnt == max) {
  26.                     int end = i;
  27.                     i = beg - 1;
  28.                     s = s.substring(0, beg) + s.substring(end + 1);
  29.                 }
  30.                 --cnt;
  31.             }
  32.         }
  33.         return s;
  34.     }
  35.    
  36.     public static void main(String args[]) {
  37.         Scanner in = new Scanner(System.in);
  38.         String input = "", res = "";
  39.         if (in.hasNextLine()) {
  40.             input = in.nextLine();
  41.         } else {
  42.             System.err.print("Нет строки");
  43.             System.exit(1);
  44.         }
  45.         int beg = -1, cnt = 0;
  46.         for (int i = 0; i < input.length(); ++i) {
  47.             if (input.charAt(i) == '(') ++cnt;
  48.             if (input.charAt(i) == ')') --cnt;
  49.             if (input.charAt(i) != '(' && input.charAt(i) != ')' && cnt == 0) {
  50.                 res += input.charAt(i);
  51.             } else if (input.charAt(i) == '(' && cnt == 1) {
  52.                 beg = i;
  53.             } else if (input.charAt(i) == ')' && cnt == 0) {
  54.                 res += work(input.substring(beg, i + 1));
  55.             }
  56.         }
  57.         System.out.println(res);
  58.         in.close();
  59.     }
  60.    
  61. }
Advertisement
Add Comment
Please, Sign In to add comment