堆叠顺序 和 推断是否成对括号
2015-10-25 14:39
225 查看
public class SqStack { public int[] data; public int top; public SqStack() { data = new int[20]; top = -1; } public boolean empty() { return top == -1; } public boolean push(int e) { if(top == 19) { return false; } top++; data[top] = e; return true; } public int[] pop() { int[] arr = new int[2]; if(top == -1) { arr[0] = 0; return arr; } arr[0] = 1; arr[1] = data[top--]; return arr; } public int[] top() { int[] arr = new int[2]; if(top == -1) { arr[0] = 0; return arr; } arr[0] = 1; arr[1] = data[top]; return arr; } public void display() { for(int i=0; i<=top; i++) { System.out.print(data[i]+ " "); } System.out.println(); } public static void main(String[] args) { SqStack ss = new SqStack(); System.out.println(ss.empty()); ss.push(2); ss.push(3); ss.display(); ss.pop(); ss.display(); ss.push(1); ss.push(2); ss.display(); ss.pop(); ss.push(4); ss.display(); ss.top(); ss.display(); } }
结果:
true 2 3 2 2 1 2 2 1 4 2 1 4
public class SqStack { public int[] data; public int top; public SqStack() { data = new int[20]; top = -1; } public boolean empty() { return top == -1; } public boolean push(int e) { if(top == 19) { return false; } top++; data[top] = e; return true; } public int[] pop() { int[] arr = new int[2]; if(top == -1) { arr[0] = 0; return arr; } arr[0] = 1; arr[1] = data[top--]; return arr; } public int[] top() { int[] arr = new int[2]; if(top == -1) { arr[0] = 0; return arr; } arr[0] = 1; arr[1] = data[top]; return arr; } public void display() { for(int i=0; i<=top; i++) { System.out.print(data[i]+ " "); } System.out.println(); } //检查括号是否配对 public boolean check(String s) { for(int i=0; i<s.length(); i++) { if(s.charAt(i) == '(') { push(1); } else if(s.charAt(i) == ')') { if(empty()) return false; else pop(); } } if(empty()) { return true; } else { return false; } } public static void main(String[] args) { SqStack ss = new SqStack(); String s = new String("(sd()f(() )d()j)"); System.out.println(ss.check(s)); s = new String("(sd()f(() ))d()j)"); System.out.println(ss.check(s)); s = new String("(sd()f((() )d()j)"); System.out.println(ss.check(s)); } }
结果:
true false false
相关文章推荐
- TypeScript学习笔记(一):介绍及环境搭建
- 可行性研究报告
- MySQL 存储过程检测表是否存在
- 【codevs 1329】东风谷早苗
- hdu(5441)——Travel
- Java 笔试:常见题目总结
- HashMap的一般用法以及遍历方法
- Linux 安装花生壳解析动态域名
- Java算法题:求素数
- R语言笔记003——set.seed()函数
- 棋盘游戏
- dispatch_sync dispatch_async有什么区别?通熟易懂的解释
- 写的一个音乐播放器界面
- Android中Broadcast Receiver组件详解
- 一个由proguard与fastJson引起的血案
- web前端之HTML简介
- Oracle 的数据类型
- codeforces #316 E. Pig and Palindromes (dp~)
- [Cocos2d塔防游戏开发]Cocos2dx-3.X完成塔防游戏《王国保卫战》--防御塔(五)之高级箭塔
- Price 中间线