*LeetCode--Valid Parentheses

Valid Parentheses    

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

自己的做法:因为不想一个一个分情况,所以考虑用map来进行数据的配对,然后用stack来进行符号的记录,

当前字符是左半边的符号时,入栈,

是右半边的符号时,进行对比,如果stack.peek()和它的另外一半相同,则出栈,否则返回false

最后,如果stack为空,则为true,否则为false

但是,事实证明,用map来装字符进行配对时的比较是错误的决定,这样会使得问题更加繁琐。

class Solution {
    public boolean isValid(String s) {
        if(s == null || s.length() == 0) return true;
        Stack<Character> stack = new Stack<>();
        Map<Character, Character> map = new HashMap<>();
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        map.put(')', '(');
        map.put(']', '[');
        map.put('}', '{');
        String str = "[{(";
        for(int i = 0; i < s.length(); i++){
            char temp = s.charAt(i);
            if(map.get(temp) != null){
                if(str.contains(String.valueOf(temp))){
                    stack.push(temp);
                } else{
                    if(!stack.empty() && stack.peek() == map.get(temp)){
                        stack.pop();
                    } else{
                        return false;
                    }
                }
            } else{
                return false;
            }
        }
        if(!stack.empty()) return false;
        return true;
    }
}

  

discuss上的解法

只利用栈,然后将可能性列出来

public boolean isValid(String s) {
	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();
}

  

还可以利用replace()方法

public class Solution {
    public boolean isValid(String s) {
        int length;
    
        do {
            length = s.length();
            s = s.replace("()", "").replace("{}", "").replace("[]", "");
        } while(length != s.length());
    
        return s.length() == 0;
    }
}

  

 


posted @ 2018-05-24 21:42  SkyeAngel  阅读(134)  评论(0编辑  收藏  举报