1 Star 0 Fork 0

Roderland/algorithm

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Question331.java 1.47 KB
一键复制 编辑 原始数据 按行查看 历史
Roderland 提交于 2021-03-15 00:46 +08:00 . ====== roderland ======
package question;
import java.util.Stack;
/**
* @author Roderland
* @since 1.0
*/
public class Question331 {
public boolean isValidSerialization(String preorder) {
String[] split = preorder.split(",");
Stack<String> stack = new Stack<>();
for (String s : split) {
if (s.equals("#")) {
while (!stack.isEmpty() && stack.peek().equals("#")) {
stack.pop();
if (stack.isEmpty()) return false;
else stack.pop();
}
}
stack.push(s);
}
return stack.isEmpty() | (stack.size()==1&stack.peek().equals("#"));
}
public boolean isValidSerialization2(String preorder) {
String[] split = preorder.split(",");
Stack<Entity> stack = new Stack<>();
for (String s : split) {
if (stack.isEmpty() && s!=split[0]) return false;
if (s.equals("#")) {
if (!stack.isEmpty()) stack.peek().count--;
} else {
stack.push(new Entity(Integer.parseInt(s)));
}
while (!stack.isEmpty() && stack.peek().count<=0) {
stack.pop();
if (!stack.isEmpty()) stack.peek().count--;
}
}
return stack.isEmpty();
}
static class Entity {
int value;
int count;
public Entity(int value) {
this.value = value;
this.count = 2;
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/Roderland/algorithm.git
git@gitee.com:Roderland/algorithm.git
Roderland
algorithm
algorithm
master

搜索帮助