LeetCode:Valid Parentheses - 合理的括號搭配

一、題目名稱java

Valid Parentheses(合理的括號搭配)code

二、題目地址leetcode

https://leetcode.com/problems/valid-parentheses/開發

三、題目內容rem

英文:Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.字符串

中文:給定一個僅包含六種括號的字符串,判斷這個字符串中的括號是否按正確的順序排列。六種括號包括小括號 ( )、中括號 [ ]、大括號 { }get

四、解題方法1input

一種方式是使用鏈表記錄遇到過的括號,每次找到反括號的時候,檢查最後添加的括號是否與當前找到的反括號匹配。string

Java代碼以下:io

import java.util.LinkedList;

/**
 * @功能說明:LeetCode 20 - Valid Parentheses
 * @開發人員:Tsybius2014
 * @開發時間:2015年11月8日
 */
public class Solution {
    
    /**
     * 合理的括號組合
     * @param s
     * @return
     */
    public boolean isValid(String s) {
       
        LinkedList<Character> linkedList = new LinkedList<Character>();
        
        for (char ch : s.toCharArray()) {
            if (ch == '(' || ch == '[' || ch == '{') {
                linkedList.add(ch);
            } else if (ch == ')') {
                if (linkedList.isEmpty() || linkedList.getLast() != '(') {
                    return false;
                } else {
                    linkedList.removeLast();
                }
            } else if (ch == ']') {
                if (linkedList.isEmpty() || linkedList.getLast() != '[') {
                    return false;
                } else {
                    linkedList.removeLast();
                }
            } else if (ch == '}') {
                if (linkedList.isEmpty() || linkedList.getLast() != '{') {
                    return false;
                } else {
                    linkedList.removeLast();
                }
            } else {
                return false;
            }
        }
        
        return linkedList.isEmpty();
    }
}

另外一種方式是使用棧(Stack)來處理,方式和上一種用鏈表的方式類似:

import java.util.Stack;

/**
 * @功能說明:LeetCode 20 - Valid Parentheses
 * @開發人員:Tsybius2014
 * @開發時間:2015年11月8日
 */
public class Solution {
    
    /**
     * 合理的括號組合
     * @param s
     * @return
     */
    public boolean isValid(String s) {
       
        Stack<Character> stack = new Stack<Character>();
        
        for (char ch : s.toCharArray()) {
            if (ch == '(') {
                stack.push(')');
            } else if (ch == '[') {
                stack.push(']');
            } else if (ch == '{') {
                stack.push('}');
            } else if (stack.isEmpty() || stack.pop() != ch) {
                return false;
            }
        }
        
        return stack.isEmpty();
    }
}

五、解題方法2

看了討論區後還發現了另外一種解題方法,即便用String類下面的replace方法,不斷消除掉相鄰的正反括號,最後沒法消除時,查看字符串內是否還有殘留字符。這種方法實現起來比較簡單,但效率比上面寫的兩種方法低不少。

Java代碼以下:

/**
 * @功能說明:LeetCode 20 - Valid Parentheses
 * @開發人員:Tsybius2014
 * @開發時間:2015年11月8日
 */
public class Solution {
    
    /**
     * 合理的括號組合
     * @param s
     * @return
     */
    public boolean isValid(String s) {
       
        int length = s.length();
        String stemp;
        do {
            stemp = s;
            s = s.replace("()", "");
            s = s.replace("[]", "");
            s = s.replace("{}", "");
            length = s.length();
        } while (length == s.length() && !stemp.equals(s));
        
        return length == 0;
    }
}

END

相關文章
相關標籤/搜索