Description
given only includes a '(', ')' string, '{', '}', '[', ']', and determine whether the string is valid.
Valid string must meet:
Left bracket must be closed by a closing parenthesis of the same type.
Left parenthesis must be closed in the correct order.
Note the empty string can be considered a valid string
Examples of
ideas
- Use the stack, each of the brackets turn into the stack, when the stack of elements coming into the brackets and top of the stack is the first one pairs [go into a left parenthesis, followed by the closing parenthesis comparison], then the top element pop-up, otherwise, the brackets into the stack.
answer - python
python有list有pop()函数,使用list代替stack
class Solution:
def isValid(self, s: str) -> bool:
stack=[]
d={'(':')','[':']','{':'}'}
for c in s:#字符串中的字符不能直接通过下标进行修改
if len(stack)>0 and c==d.get(stack[-1],'?'):
#c为),},或],top中的应为左括号 ([)()])不是有效的括号
stack.pop()
else:
stack.append(c)
return len(stack)==0
- c++
class Solution {
public:
bool isValid(string s) {
stack<char> st;
unordered_map<char,char> dict={{'(',')'},{'[',']'},{'{','}'}};
for (char c: s)
{
if (!st.empty() && (dict[st.top()]==c))
st.pop();
else
st.push(c);
}
return st.empty();
}
};