標籤:java演算法 括弧問題
下面的代碼用於判斷一個串中的括弧是否匹配所謂匹配是指不同類型的括弧必須左右呼應,可以相互包含,但不能交叉
例如: ..(..[..]..).. 是允許的; ..(…[…)….]…. 是禁止的
對於 main 方法中的測試案例,應該輸出: false true false false
public class 括弧問題 { public static boolean isGoodBracket(String s) { Stack<Character> a = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == ‘(‘) // 將每個第一次匹配的括弧的匹配括弧加入到棧中去 a.push(‘)‘); if (c == ‘[‘) a.push(‘]‘); if (c == ‘{‘) a.push(‘}‘); if (c == ‘)‘ || c == ‘]‘ || c == ‘}‘) { // 遇到結束的括弧的時候進行判斷 if (a.size() == 0) // 就是棧中沒有資料 return false; // 填空 if (a.pop() != c) // 如果遇到的和彈出的不一致的話也就是出現重疊 return false; } } if (a.size() != 0) // 到最後棧中還有元素的話,也是屬於不匹配的類型 return false; // 填空 return true; } public static void main(String[] args) { System.out.println(isGoodBracket("...(..[.)..].{.(..).}...")); System.out.println(isGoodBracket("...(..[...].(.).).{.(..).}...")); System.out.println(isGoodBracket(".....[...].(.).){.(..).}...")); System.out.println(isGoodBracket("...(..[...].(.).){.(..)....")); }}
Java演算法-括弧問題