Created
February 8, 2011 11:32
-
-
Save dizzi/816296 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String exp = "(x+(xx)+((xxx)+))+"; | |
int close=-1, open=-1; | |
boolean check = true, hasCandidate = false; | |
int counter = 0; | |
for(int nextStart = exp.length()-1; nextStart!=0; ){ | |
check = true; hasCandidate = false; counter = 0; | |
close = open = -1; | |
for(int i = nextStart; i>=0; i--){ // for every special character | |
if(exp.charAt(i)=='+' && i-1>=0 && exp.charAt(i-1)==')' && check){ // if firste checked specChar preceed by ) | |
check = false; | |
nextStart=i-1; // shift next pass | |
close = i + 1; // set closing position | |
if(i+1<exp.length() && exp.charAt(i+1)==')'){ // if ) follows it can be already bracketed | |
hasCandidate = true; // its only candidate | |
} | |
} else if(!check){ // ok count closing and opening brackets | |
if(exp.charAt(i)==')') | |
counter++; | |
if(exp.charAt(i)=='(') | |
counter--; | |
if(counter==0){ // its zero, we should place bracket here | |
if(hasCandidate){ // if this is candidate check if it has closing bracket if yes, forget it | |
if((i-1>=0)&&exp.charAt(i-1)=='(') | |
break; | |
} | |
open = i; | |
break; | |
} | |
} | |
if(i==0 && check){ // if we processed all the specchars and our index is 0, just break; | |
nextStart=0; | |
} | |
} | |
if(open >= 0 && close>= 0){ // process only non negative intervals | |
System.out.println(String.format("%d %d", open, close)); | |
StringBuffer sb = new StringBuffer(exp); | |
sb.insert(close, ']'); | |
sb.insert(open, '['); | |
exp = sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment