request: 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
思路一:用stack记录正向括号,每当遇到反向括号时,将stack中pop出来一个,检查这个正括号是否与正括号一样,如果一样,则返回true,如果不一样,则返回false,直到最后,检查stack是否为空。
public class Solution{
public boolean isValid(String s){
Stack<Character> mark=new Stack<Character>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='(' ||s.charAt(i)=='[' || s.charAt(i)=='}'){
mark.push(s.charAt(i));
}else if(s.charAt(i)==')' || s.charAt(i)==']' || s.charAt(i)=='}')
if(mark.isEmpty())
return false;
char cur=mark.pop();
if(cur=='(' &&s.charAt(i)!=')')
return false;
if(cur=='[' &&s.charAt(i)!=']')
return false;
if(cur=='{' &&s.charAt(i)!='}')
return false;
}
}
if(mark.isEmpty()) return true;
return false;
}
}
Python:利用字典,找出对应,利用stack,同上面的道理。
class Solution: def isValid(self,s): stack=[] lookup={"(": ")"; "[": "]"; "{": "}" } for parentheses in s: if parentheses in lookup: stack.append(parenthese) elif len(stack)==0 or lookup[stack.pop()]!=parentheses: return flase return len(stack)==0
小梦想家的leetcode