Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
本题是简单匹配问题,用stack最优。时间:2ms
我的代码:
class Solution { public: bool isValid(string s) { stack<char> sign; for (string::const_iterator iter = s.begin(); iter != s.end(); ++iter){ switch (*iter){ case '(': case '{': case '[':sign.push(*iter); break; case ')': if (sign.size()&&sign.top() == '('){ sign.pop(); break; } case '}': if (sign.size() && sign.top() == '{'){ sign.pop(); break; } case ']': if (sign.size() && sign.top() == '['){ sign.pop(); break; } return false; default:break; } } if (sign.size()) return false; else return true; } };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
 
                    
                     
                    
                 
                    
                 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号