leetcode_6. Effective brackets

  • Effective parentheses :
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
    左括号必须用相同类型的右括号闭合。
    左括号必须以正确的顺序闭合。
    注意空字符串可被认为是有效字符串。
示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true
  • There is no specific application through the function STL template library, here found a relatively simple, the core is the use of the stack, advanced stack of a legal character behind the character if left bracket to then into the stack, if it is left bracket verify whether the match the symbol stack, the stack if the matching symbols from the stack, continue to determine subsequent characters until the stack is empty, if no match is empty, return false
class Solution {
public:
    bool isValid(string s) {
        if(s.length()==0)   return true;
        if(s.length()==1)    return false;
        stack<char>ss;
        int index = 0;
        while(index<s.length())
        {
            if(s[index]=='('||s[index]=='{'||s[index]=='[') ss.push(s[index]);
            else if(s[index]==')') {
                if(ss.empty()||ss.top()!='(')   return false;
                ss.pop();
            }
            else if(s[index]=='}') {
                if(ss.empty()||ss.top()!='{')   return false;
                ss.pop();
            }
            else if(s[index]==']') {
                if(ss.empty()||ss.top()!='[')   return false;
                ss.pop();
            }
            ++index;
        }
        if(!ss.empty()) return false;
        return true;
    }
};
Published 77 original articles · won praise 19 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_42932834/article/details/95242550