Swift算法:Verify Preorder Serializ
![](https://img.haomeiwen.com/i1169201/4b481c602b6ff663.png)
题目
class Solution {
func isValidSerialization(preorder: String) -> Bool {
if preorder == "" || preorder == "#,#" {
return false
}
if preorder == "#" {
return true
}
let array = preorder.componentsSeparatedByString(",")
var stack: [String] = []
for i in 0 ..< array.count {
stack.append(array[i])
while checkTop(stack) {
for _ in 0 ..< 3 {
stack.popLast()
}
if stack.count == 0 {
if i == array.count-1 {
return true
} else {
return false
}
}
stack.append("#")
}
}
return false
}
func checkTop(stack: [String]) -> Bool {
let count = stack.count
guard count > 1 else {
return false
}
if stack[count-1] == "#" && stack[count-2] == "#" {
return true
} else {
return false
}
}
}
本文标题:Swift算法:Verify Preorder Serializ
本文链接:https://www.haomeiwen.com/subject/esuhrttx.html
网友评论