# 28. 最长合法表达式

28 28-1

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

const lines = [];
rl.on('line', (line) => {
    let expressions = extract(line);
    expressions.sort((a,b)=>a.length - b.length);
    if (expressions.length) {
        console.log(calc(expressions[0]));
    } else {
        console.log(0);
    }
});

function extract(line) {
    let expressions = [];
    let start = -1;
    for(let i=0; i<line.length; i++) {
        let cur = line.charAt[i];
        if (!isNaN(cur)) {// 数字
            if (start === -1) {
                start === i;
            }
        } else if (start !== -1 && '+-*'.includes(cur)) {
            if (!'+-*'.includes(line[i-1])) {
                i++;
            } else {
                expressions.push(line.substring(start, i));
                start = -1;
            }
        } else {
            if (start !== -1) {
                expressions.push(line.substring(start, i));
                start = -1;
            }
        }
        if (start !== -1) {
            expression.push(line.substring(start));
        }
    }
    return expressions;
}

function calc(str) {
    let tokens = [];
    let number = '';
    for(let ch of str) {
        if (!isNaN(ch)) {
            number += ch;
        } else {
            tokens.push(number);
            tokens.push(ch);
            number = '';
        }
    }
    tokens.push(number);
    for(let i=0; i<tokens.length; i++) {
        if (tokens[i] === '*') {
            let res = parseInt(tokens[i-1]) * parseInt(tokens[i+1]);
            tokens[i-1] = String(res);
            tokens.splice(i, 2);
            i--;
        }
    }
    let res = parseInt(tokens[0]);
    for(let i=1; i<tokens.length; i+=2) {
        if (tokens[i] === '+') {
            res += parseInt(tokens[i+1]);
        } else {
            res -= parseInt(tokens[i-1]);
        }
    }
    return res;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77