您的位置:首页 > 其它

题目1153:括号匹配问题

2014-02-16 20:37 459 查看
import java.io.IOException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Stack;
import java.util.Comparator;

class Node implements Comparator<Node>
{
public Node(char c, int p)
{
ch = c;
pos = p;
}

public int compare(Node a, Node b)
{
return a.pos - b.pos;
}

public char ch;
public int pos;
}

class Main
{
public static final boolean DEBUG = false;

public static void main(String[] args) throws IOException
{
BufferedReader cin;
String s;

if (DEBUG) {
cin = new BufferedReader(new FileReader("d:\\OJ\\uva_in.txt"));
} else {
cin = new BufferedReader(new InputStreamReader(System.in));
}

while ((s = cin.readLine()) != null) {
System.out.println(s);

Stack<Node> stack = new Stack<Node>();

for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(') {
stack.push(new Node(ch, i));
} else if (ch == ')') {
if (!stack.isEmpty() && stack.peek().ch == '(') {
stack.pop();
} else {
stack.push(new Node(ch, i));
}
}
}

StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
sb.append(' ');
}

while (!stack.isEmpty()) {
Node tmp = stack.peek();
stack.pop();

if (tmp.ch == '(') {
sb.setCharAt(tmp.pos, '$');
} else {
sb.setCharAt(tmp.pos, '?');
}
}

System.out.println(sb.toString());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: