使用一个栈实现, 遇到#出栈,最终比较栈内元素
type Stack struct {
top int
data []interface{}
}
func (this *Stack) Push(i interface{}) {
this.data = append([]interface{}{i}, this.data...)
}
func (this *Stack) Peek() interface{} {
return this.data[0]
}
func (this *Stack) Pop() (interface{}, bool) {
if len(this.data) == 0 {
return nil, false
}
i := this.Peek()
this.data = this.data[1:]
return i, true
}
func backspaceCompare(S string, T string) bool {
st1 := &Stack{}
st2 := &Stack{}
foo(st1, S)
foo(st2, T)
r1 := bar(st1)
r2 := bar(st2)
return r1 == r2
}
func foo(st *Stack, s string) {
for _, v := range s {
if string(v) == "#" {
st.Pop()
} else {
st.Push(byte(v))
}
}
}
func bar(st *Stack) string {
result := strings.Builder{}
for {
v, ok := st.Pop()
if !ok {
break
}
result.WriteByte(v.(byte))
}
return result.String()
}