首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

括号婚配、进制转换与堆栈

2012-10-11 
括号匹配、进制转换与堆栈定义堆栈接口:?package stackpublic class Client {public static void main(Str

括号匹配、进制转换与堆栈

定义堆栈接口:

?

package stack;public class Client {public static void main(String[] args) {//baseConversion(8);System.out.println(bracketMatch("{[wf(wf)]}"));}// 进制转换算法public static void baseConversion(int val) {Stack s = new StackSLinked();while (val > 0) {s.push(val % 8 + "");val = val / 8;}while (!s.isEmpty())try {System.out.print((String) s.pop());} catch (StackEmptyException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 括号匹配算法public static boolean bracketMatch(String str) {Stack s = new StackSLinked();for (int i = 0; i < str.length(); i++) {char c = str.charAt(i);switch (c) {case '{':case '[':case '(':s.push(Integer.valueOf(c));break;case '}':try {if (!s.isEmpty() && ((Integer) s.pop()).intValue() == '{')break;elsereturn false;} catch (StackEmptyException e) {// TODO Auto-generated catch blocke.printStackTrace();}case ']':try {if (!s.isEmpty() && ((Integer) s.pop()).intValue() == '[')break;elsereturn false;} catch (StackEmptyException e) {// TODO Auto-generated catch blocke.printStackTrace();}case ')':try {if (!s.isEmpty() && ((Integer) s.pop()).intValue() == '(')break;elsereturn false;} catch (StackEmptyException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}if (s.isEmpty())return true;elsereturn false;}}
?

热点排行