题目:
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.
这道题目和四则运算表达式求值比较类似,只需要用一个栈即可实现,具体方法为检测到左括号就入栈,检测到右括号就出栈,并将检测的右括号和出栈的左括号匹配,知道所有的都匹配时才为真。
时间复杂度:O(n)
实现:
class Solution {
public:
	bool isValid(string s) {
		if (s.size() < 2) return false;
		stack<char> myStack;
		for (int i = 0; s[i] != '\0'; i++)
		{
			if (s[i] == '(' || s[i] == '{' || s[i] == '[') myStack.push(s[i]);
			else if (myStack.empty()) return false;
			else
			{
				char temp = myStack.top();
				myStack.pop();
				if (temp + 1 == s[i] || temp + 2 == s[i]) continue;
				else return false;
			}
		}
		if (myStack.empty())       //A
			return true;
		return false;
	}
};注意:A处
 
                   
                   
                   
                   
                             本文介绍了一种使用栈数据结构来验证括号是否正确配对的方法。对于包含'(',')','{','}
 本文介绍了一种使用栈数据结构来验证括号是否正确配对的方法。对于包含'(',')','{','}
           
       
           
                 
                 
                 
                 
                 
                
               
                 
                 
                 
                 
                
               
                 
                 扫一扫
扫一扫
                     
              
             
                  
 被折叠的  条评论
		 为什么被折叠?
被折叠的  条评论
		 为什么被折叠?
		 
		  到【灌水乐园】发言
到【灌水乐园】发言                                
		 
		 
    
   
    
   
             
            


 
            