Skip to content

Instantly share code, notes, and snippets.

@zyxar
Created October 11, 2012 05:08
Show Gist options
  • Save zyxar/3870298 to your computer and use it in GitHub Desktop.
Save zyxar/3870298 to your computer and use it in GitHub Desktop.
solution to #amazon hiring final4 test2: stack sequence
package main
import (
"fmt"
"strconv"
"strings"
"os"
"bufio"
)
type Stack struct {
store []int
top, capa int
}
func NewStack(capa int) *Stack {
s := new(Stack)
s.store = make([]int, capa)
s.top = 0
s.capa = capa
return s
}
func (id *Stack) push(i int) {
if id.top == id.capa {
panic("stack overflow!")
}
id.store[id.top] = i
id.top++
}
func (id *Stack) pop() int {
if id.top == 0 {
panic("stack overflow!")
}
id.top--
return id.store[id.top]
}
func (id *Stack) peek() int {
if id.top == 0 {
return -1
}
return id.store[id.top-1]
}
func (id *Stack) isempty() bool {
return !(id.top > 0)
}
func convert(s string) ([]int, int) {
ss := strings.Split(s, " ")
ret := make([]int, len(ss))
for i := 0; i < len(ss); i++ {
ret[i], _ = strconv.Atoi(ss[i])
}
return ret, len(ss)
}
func getSeq(input1, input2 string) string {
origin, len1 := convert(input1)
result, len2 := convert(input2)
if len1 != len2 {
return "None"
}
i, j := 1, 0
mark := make(map[int]int)
for k := 0; k < len1; k++ {
mark[origin[k]] = k + 1
}
stack := NewStack(len1)
stack.push(origin[0])
ret := "push1"
for i < len1 || !stack.isempty() {
if !stack.isempty() && stack.peek() == result[j] {
a := stack.pop()
j++
ret += "|pop" + strconv.Itoa(mark[a])
} else {
if i == len1 {
break
}
stack.push(origin[i])
ret += "|push" + strconv.Itoa(mark[origin[i]])
i++
}
}
if j != len1 {
return "None"
}
return string(ret)
}
func main() {
stdin := bufio.NewReader(os.Stdin)
var seq string
for {
origin, err := stdin.ReadString('\n')
if err != nil {
break
}
result, err := stdin.ReadString('\n')
if err != nil {
break
}
origin = strings.TrimRight(origin, "\n")
result = strings.TrimRight(result, "\n")
seq = getSeq(origin, result)
fmt.Println(seq)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment