Java堆疊Stack的實用小例子
阿新 • • 發佈:2019-02-05
public static void main(String[] args) { change(4587788); String str = "()";//測試一段程式碼所使用的括號是否正確 System.out.println(bracketMatch(str)); } public static void change(int x) { Stack stack = new Stack();//棧的特點是先進後出,後進先出,用於進位制之間的轉化很方便 十進位制轉八進位制 while (x > 0) { stack.push(x % 8); x /= 8; } while (!stack.isEmpty()) { System.out.print(stack.pop() + ""); } System.out.println(""); } public static boolean bracketMatch(String str) { Stack stack = new Stack(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); switch (c) { case '{': case '[': case '(': stack.push(Integer.valueOf(c)); break; case '}': if (!stack.isEmpty() && ((Integer) stack.pop()).intValue() == '{') break; else return false; case ']': if (!stack.isEmpty() && ((Integer) stack.pop()).intValue() == '[') break; else return false; case ')': if (!stack.isEmpty() && ((Integer) stack.pop()).intValue() == '(') break; else return false; } } if (stack.isEmpty()) return true; else return false; }