장난감
PostFix
by umaking
2011. 7. 19.
public class PostFixTest {
private ArrayList<String>stack = new ArrayList<String>();
@Test
public void test1() {
StringBuffer sb = new StringBuffer();
ArrayList<String>arr = new ArrayList<String>();
String s = "(1+2*(10+20-(7*10)-1))";
Pattern p = Pattern.compile("(\\d+)|([\\+\\-\\*\\/])|([\\(\\)])");
Matcher m = p.matcher(s);
int i;
while(m.find()) {
for(i = 1; i <= m.groupCount(); i++) {
if(m.group(i) == null) continue;
arr.add(m.group(i));
}
}
for(i = 0; i < arr.size(); i++) {
char w = arr.get(i).charAt(0);
if(w == '+' || w == '-' || w == '*' || w == '/') {
push(arr.get(i));
}else if(w == '(') {
}else if(w == ')') {
sb.append(pop() + " ");
}else {
sb.append(arr.get(i) + " ");
}
}
while((s = pop()) != null) {
sb.append(s + " ");
}
System.out.println(sb.toString());
}
public void push(String str) {
stack.add(str);
}
public String pop() {
if(stack.size() <= 0) {
return null;
}
int pos = stack.size()-1;
String str = stack.get(pos);
stack.remove(pos);
return str;
}
}