Thursday, October 10, 2013

20. Valid Parentheses (easy)

Given a string s 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.
  3. Every close bracket has a corresponding open bracket of the same type.

 

Example 1:

Input: s = "()"

Output: true

Example 2:

Input: s = "()[]{}"

Output: true

Example 3:

Input: s = "(]"

Output: false

Example 4:

Input: s = "([])"

Output: true

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.
A:
就是 大一的时候的 stack 的课后题,   用一个stack, 来保持左括号。  -----


------------转换成数字是没有必要的。  完全是多余********************
Mistakes:
1: 又一次,华丽丽地,忘了update i,j 指针。
2: 题意没有领会透彻。  ()[]{}  也是可以的。

--------------------2nd pass--------------------
class Solution {
public:
bool isValid(string s) {
unordered_map<char, char> map{{')','('}, {'}', '{'}, {']', '['}};
vector<char> V;
for(auto ch : s){
if(ch == '(' || ch == '{' || ch == '['){
V.push_back(ch);
}else {
if (!V.empty() && V.back() == map[ch])
V.pop_back();
else
return false;
}
}
return V.empty();
}
};
Learned:
LC 上的题目,基本都是应该十几二十行搞定的。
如果if 里面再带一层if。  然后后面还有 else的话, else会找最近的if (如果没有大括号来帮忙)

No comments:

Post a Comment