题目来自《算法》第四版习题1.3.9,原题如下:
Write a program that takes from standard input an expression without left parentheses and prints the equivalent infix expression with the parentheses inserted. For example, given the input:
1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )
your program should print
( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) )
大概意思就是输入一个不带左括号的表达式,补全左括号。
初看我实在没什么想法,后来拿了一只笔,在纸上演算了一下,发现补全左括号实际上就相当于补全右括号,分析过程也是相当简单,最简单的情况不外乎以下三种:
1、(a+b a+b型,直接在后面补右括号即可
2、((... a是括号型,递归调用自己
3、(a+( a+括号型,输出a+,递归调用自己
很显然,需要定义一个函数CompleteBracket来实际递归:
1、取字符串,输出之,如果是左括号,则递归调用本函数(a)
2、取字符串,输出之(运算符)
3、取字符串,输出之,如果是左括号,则递归调用本函数(b)
4、输出右括号
代码实现如下:
View Code
import java.util.Scanner; public class Program { public static void main(String args[]) { In in = new In(new Scanner("( ( 1 + 2 * ( ( 3 - 4 * ( 5 - 6")); CompleteBracket(in); StdOut.println(); } private static void CompleteBracket(In in) { if (in.isEmpty()) return; String p1 = in.readString(); Output(p1); if (p1.equals("(")) CompleteBracket(in); if (in.isEmpty()) return; String op = in.readString();; Output(op); if (in.isEmpty()) return; String p2 = in.readString();; Output(p2); if (p2.equals("(")) CompleteBracket(in); Output(")"); } private static void Output(String s) { StdOut.printf("%s ", s); } }
实际了补全右括号,补全左括号其实就是将字符串反转,然后将右括号看作左括号进行处理,然后再进行反转即可:
View Code
import java.util.Scanner; public class Program { private static String buffer = ""; public static void main(String args[]) { String pattern = "1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )"; pattern = new StringBuffer(pattern).reverse().toString(); In in = new In(new Scanner(pattern)); CompleteBracket(in); buffer = new StringBuffer(buffer).reverse().toString(); StdOut.println(buffer); } private static void CompleteBracket(In in) { if (in.isEmpty()) return; String p1 = in.readString(); Output(p1); if (p1.equals(")")) CompleteBracket(in); if (in.isEmpty()) return; String op = in.readString();; Output(op); if (in.isEmpty()) return; String p2 = in.readString();; Output(p2); if (p2.equals(")")) CompleteBracket(in); Output("("); } private static void Output(String s) { buffer += String.format("%s ", s); } }
代码中用到了一些书中提到的库,可以在官方网站上下载:
http://algs4.cs.princeton.edu/home/