FB面经 Prepare: Make Parentheses valid
给一组括号,remove最少的括号使得它valid
从左从右各scan一次
1 package fb; 2 3 public class removeParen { 4 5 public static String fix(String str) { 6 StringBuffer res = new StringBuffer(str); 7 int l = 0, r = 0; 8 int i = 0; 9 while (i < res.length()) { 10 if (res.charAt(i) == '(') l++; 11 else { 12 if (l <= r) { 13 res.deleteCharAt(i); 14 i--; 15 } 16 else { 17 r++; 18 } 19 } 20 i++; 21 } 22 23 l = 0; 24 r = 0; 25 i = res.length()-1; 26 while (i >= 0) { 27 if (res.charAt(i) == ')') r++; 28 else { 29 if (l >= r) { 30 res.deleteCharAt(i); 31 } 32 else { 33 l++; 34 } 35 } 36 i--; 37 } 38 39 return res.toString(); 40 } 41 42 43 /** 44 * @param args 45 */ 46 public static void main(String[] args) { 47 // TODO Auto-generated method stub 48 String res = fix(")((())("); 49 System.out.println(res); 50 } 51 52 }