题目解析
在给定式子其中,将带括号的算式进行拆解,并输出
解题思路
简单的栈应用 —— 《括号匹配问题》
如果当前字符不是 ) 时,则将字符存入栈中。
否则遇到 ) 时, 则将栈中字符弹出,直到弹出 ( 为止。 注:弹出的字符需要倒序显示。
代码
import java.io.*;
public class Main
{
static Stack<Character> st = new Stack<Character>();
static void print()
{
StringBuilder s = new StringBuilder();
// 如果栈顶的元素不是"(",则一直弹出字符
while (st.peek() != '(') s.append(st.pop());
st.pop(); // 弹出最后的 "("
s.reverse(); // 反转字符串
out.println(s);
}
public static void main(String[] args)
{
String S = sc.next();
char s[] = S.toCharArray();
for (int i = 0; i < s.length; i++)
{
if (s[i] == ')') print(); // 如果遇到 ")" , 则将栈中的字符弹出
else st.add(s[i]); // 将元素压入栈中
}
out.flush();
out.close();
}
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
}