-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommon.go
93 lines (70 loc) · 1.44 KB
/
common.go
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"bufio"
"fmt"
"os"
"regexp"
"strconv"
"strings"
)
var isNum = regexp.MustCompile("^-?[0-9]+$")
type Stack []string
func (s *Stack) Empty() bool {
return len(*s) == 0
}
func (s *Stack) Top() string {
return (*s)[len(*s)-1]
}
func (s *Stack) Pop() string {
top, stack := (*s)[len(*s)-1], (*s)[:len(*s)-1]
*s = stack
return top
}
func (s *Stack) Push(x string) {
*s = append(*s, x)
}
type Queue []string
func (q *Queue) Empty() bool {
return len(*q) == 0
}
func (q *Queue) Enqueue(x string) {
*q = append(*q, x)
}
func (q *Queue) Dequeue() string {
head, tail := (*q)[0], (*q)[1:]
*q = tail
return head
}
func solveReversePolish(q Queue) int {
stack := Stack{}
for !q.Empty() {
item := q.Dequeue()
switch item {
case "+":
t1, _ := strconv.Atoi(stack.Pop())
t2, _ := strconv.Atoi(stack.Pop())
stack.Push(strconv.Itoa(t1 + t2))
case "*":
t1, _ := strconv.Atoi(stack.Pop())
t2, _ := strconv.Atoi(stack.Pop())
stack.Push(strconv.Itoa(t1 * t2))
default:
stack.Push(item)
}
}
res, _ := strconv.Atoi(stack.Pop())
return res
}
func main() {
sum := 0
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
// adding spaces around parenthesis to tokenize them
line = strings.ReplaceAll(line, "(", " ( ")
line = strings.ReplaceAll(line, ")", " ) ")
fields := strings.Fields(line)
sum += solveReversePolish(ShuntingYard(fields))
}
fmt.Println(sum)
}