Skip to content

Instantly share code, notes, and snippets.

@rfaisal
Created July 13, 2013 08:40
Show Gist options
  • Select an option

  • Save rfaisal/5990004 to your computer and use it in GitHub Desktop.

Select an option

Save rfaisal/5990004 to your computer and use it in GitHub Desktop.
public class CompletingBrackets {
public static String complete(String text){
StringBuilder result= new StringBuilder();
int count=0;
for(int i=0;i<text.length();i++){
if(text.charAt(i)=='[') count++;
else if(text.charAt(i)==']') count--;
}
if(text.charAt(0)==']'){
result.append('[');
count++;
}
if(count>0){
result.append(text);
while(count-->0) result.append(']');
}
else{
while(count++<0) result.append('[');
result.append(text);
}
return result.toString();
}
}
public class CompletingBracketsTest {
@Test
public void testComplete() {
assertEquals("[[]]", CompletingBrackets.complete("[["));
assertEquals("[][]", CompletingBrackets.complete("]["));
assertEquals("[[[[]]]]", CompletingBrackets.complete("[[[[]]]]"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment