Java演算法-括弧問題

來源:互聯網
上載者:User

標籤: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演算法-括弧問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.