酷狗笔试题:补齐左括号(栈)
描述:
//输入1+2)*3-4)*5-6))) //输出((1+2)*((3-4)*(5-6)))
代码:
import java.util.*; public class G { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine().trim(); String result = getfullstr(str); System.out.println(result); } public static String getfullstr(String str) { Stack<String> lefts = new Stack<>(); Stack<String> rights = new Stack<>(); char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (c == '+' || c == '-' || c == '+' || c == '*' || c == '/') { rights.add(c + ""); } else if (c == ')') { String lstr1 = lefts.pop(); String lstr2 = lefts.pop(); String rstr1 = rights.pop(); lefts.add("(" + lstr2 + rstr1 + lstr1 + ")"); } else if (Character.isDigit(chars[i])) { String num = c + ""; while ((i + 1) < chars.length && Character.isDigit(chars[i + 1])) { num += c; i++; } lefts.add(num); } } while (rights.size() > 0) { String lstr1 = lefts.pop(); String lstr2 = lefts.pop(); String rstr1 = rights.pop(); lefts.add("(" + lstr2 + rstr1 + lstr1 + ")"); } String result = ""; while (lefts.size() > 0) { result = lefts.pop() + result; } return result; } }