-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path245.go
92 lines (80 loc) · 1.58 KB
/
245.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
// UVa 245 - Uncompress
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
var words []string
func isAlphabet(b byte) bool { return b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' }
func isDigit(b byte) bool { return b >= '0' && b <= '9' }
func moveToFront(word string, idx int) {
if idx != -1 {
words = append(words[:idx], words[idx+1:]...)
}
words = append([]string{word}, words...)
}
func push(word string) {
idx := -1
for i, w := range words {
if w == word {
idx = i
}
}
moveToFront(word, idx)
}
func uncompress(pos int) string {
moveToFront(words[pos], pos)
return words[0]
}
func parse(line string) string {
var uncompressed strings.Builder
var word, pos string
var idx int
for i := range line {
if isAlphabet(line[i]) {
word += string(line[i])
} else {
if len(word) > 0 {
uncompressed.WriteString(word)
push(word)
word = ""
}
if isDigit(line[i]) {
pos += string(line[i])
} else {
if len(pos) > 0 {
fmt.Sscanf(pos, "%d", &idx)
uncompressed.WriteString(uncompress(idx - 1))
pos = ""
}
uncompressed.WriteByte(line[i])
}
}
}
if len(word) > 0 {
uncompressed.WriteString(word)
push(word)
}
if len(pos) > 0 {
fmt.Sscanf(pos, "%d", &idx)
uncompressed.WriteString(uncompress(idx - 1))
}
return uncompressed.String()
}
func main() {
in, _ := os.Open("245.in")
defer in.Close()
out, _ := os.Create("245.out")
defer out.Close()
s := bufio.NewScanner(in)
s.Split(bufio.ScanLines)
var line string
for s.Scan() {
if line = s.Text(); line == "0" {
break
}
fmt.Fprintln(out, parse(line))
}
}