LeetCode - 20. Valid Parentheses

題目:

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.


思路與步驟:

如果是前半個括號,直接輸入;如果是後半個,則進行匹配。所以遇到兩個問題:

1. 用什麼數據結構來存儲括號;

2. 後半個匹配時的邏輯。

問題解決:

    由於後半個匹配是要與最後一個輸入的來匹配(注意這裏的邏輯關係),所以可以直接用list,最經典的做法是用stack;同理第二個問題也得到解決,即讀入一個後半括號時,只有與上一個匹配纔是匹配。

一種巧妙解法:

    上面提到的不管是用list還是stack,基本思路是一致的,只是數據結構的選擇不一樣。還有一種比較巧妙的思路,直接將前半個括號對應的後半個輸入stack,後面直接判斷是否相等即可。這樣可以使代碼更加簡潔


編程實現:

    這個問題的解決又複習了 Java 的 stack.

用List,更快:

public class Solution {
    public boolean isValid(String s) {
        //method-1: My own solution with list, faster than stack
        char[] c = s.toCharArray();
        if(s.length() == 0 || s.length()%2 == 1 || c[0] == ')' || c[0] == ']' || c[0] == '}') return false;
        List<Character> list = new ArrayList<Character>();
        for(int i=0; i<s.length(); i++){
            if(c[i] == '(' || c[i] == '[' || c[i] == '{')     list.add(c[i]);
            else if(c[i] == ')'){
                if(list.get(list.size()-1) == '(')  list.remove(list.size()-1);
                else return false;
            } else if(c[i] == ']'){
                if(list.get(list.size()-1) == '[')  list.remove(list.size()-1);
                else return false;
            } else if(c[i] == '}'){
                if(list.get(list.size()-1) == '{')  list.remove(list.size()-1);
                else return false;
            }
        }
        if(list.size()==0) return true;
        else return false;
        /*//這一段效率不如上面那一段
        for(int i=0; i<s.length(); i++){
            if(c[i] == '(' || c[i] == '[' || c[i] == '{')     list.add(c[i]);
            else if(c[i] == ')' && list.get(list.size()-1) == '(') list.remove(list.size()-1);
            else if(c[i] == ']' && list.get(list.size()-1) == '[') list.remove(list.size()-1);
            else if(c[i] == '}' && list.get(list.size()-1) == '{') list.remove(list.size()-1);
            else return false;
        }
        return list.size()==0 ? true : false;
        */
    }
}

用stack:

public class Solution {
    public boolean isValid(String s) {
        //method-2: classic solution with stack
        Stack<Character> stack = new Stack<Character>();
	    for (char c : s.toCharArray()) {
		    if (c == '(' || c == '[' || c == '{')   stack.push(c);
		    else if(c == ')' && !stack.isEmpty() && stack.peek() == '(')   stack.pop();
		    else if(c == ']' && !stack.isEmpty() && stack.peek() == '[')   stack.pop();
		    else if(c == '}' && !stack.isEmpty() && stack.peek() == '{')   stack.pop();
		    else return false;
	    }
	    return stack.isEmpty();
    }
}

用stack,很巧妙的一種方法:

public class Solution {
    public boolean isValid(String s) {
        //method-3: an interesting solution with stack
        Stack<Character> stack = new Stack<Character>();
	    for (char c : s.toCharArray()) {
		    if (c == '(')   stack.push(')');
		    else if (c == '{')  stack.push('}');
		    else if (c == '[')  stack.push(']');
		    else if (stack.isEmpty() || stack.pop() != c)   return false;
	    }
	    return stack.isEmpty();
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章