Leetcode 20 Valid Parentheses
阿新 • • 發佈:2018-12-15
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- 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
這個題是簡單的字串匹配
1)
class Solution { public boolean isValid(String s) { if(s == null || s.length() < 1){ return true; }else if(s.length() == 1){ return false; } Stack<Character> stack = new Stack<>(); for(int i = 0 ; i < s.length();i++){ if(s.charAt(i) != ')' && s.charAt(i) != ']' && s.charAt(i) != '}'){ stack.push(s.charAt(i)); }else{ if(!stack.isEmpty() && stack.peek() == '(' && s.charAt(i) == ')'){ stack.pop(); }else if(!stack.isEmpty() && stack.peek() == '[' && s.charAt(i) == ']'){ stack.pop(); }else if(!stack.isEmpty() && stack.peek() == '{' && s.charAt(i) == '}'){ stack.pop(); }else{ return false; } } } if(!stack.isEmpty()){ return false; }else{ return true; } } }
2)
class Solution { public boolean isValid(String s) { int top = -1; char[] cs = s.toCharArray(); for(int i=0;i<s.length();i++){ if(top < 0 || !ism(cs[top], cs[i])){ top++; cs[top] = cs[i];// 如果只有一種括號就不需要這行 } else top--; } return top == -1; } public boolean ism(char c1, char c2){ if(c1 == '(' && c2 ==')') return true; if(c1 == '[' && c2 ==']') return true; if(c1 == '{' && c2 =='}') return true; return false; } }