FB面经 Prepare: Make Parentheses valid
Posted neverlandly
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于FB面经 Prepare: Make Parentheses valid的主要内容,如果未能解决你的问题,请参考以下文章
FB面经 Prepare: K closest point to the origin
Groupon面经Prepare: Max Cycle Length
G面经Prepare: Print Zigzag Matrix
M面经Prepare: Find integer Average of 2 integers.
G面经Prepare: Longest All One Substring
Groupon面经Prepare: Sort given a range && Summary: Bucket Sort