1.3.9 左括号补全

String s = "1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )";

LinkedStack ops = new LinkedStack<>();
LinkedStack vals = new LinkedStack<>();

for(int i = 0 ; i < s.length(); i++){
    char c = s.charAt(i);
    
    switch(c){
    case '+':
    case '-':
    case '*':
    case '/':
        ops.push(c + "");
        break;
        
    case ')':
        String sec = vals.pop();
        String fir = vals.pop();
        String op  = ops.pop();
        vals.push("(" + fir + op + sec + ")");
        break;
    case ' ':
        break;
    default:
            vals.push(c + "");
    }
}

System.out.println(vals.pop());
Paste_Image.png

你可能感兴趣的:(1.3.9 左括号补全)