• 20. Valid Parentheses


    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.


    模拟操作

    #include <iostream>
    #include <vector>
    #include <set>
    #include <algorithm>
    #include <string>
    #include <sstream>
    #include <cstring>
    #include <cmath>
    #include <stack>
    using namespace std;
    
    class Solution {
    public:
    	bool isValid(string s) {
    		if (s.size() == 1)
    		{
    			return false;
    		}
    		stack<char>sta;
    		char ch;
    		for (auto iter = s.begin(); iter != s.end(); iter++)
    		{
    			ch = *iter;
    			if (ch == '(' || ch == '{' || ch == '[')
    			{
    				sta.push(ch);
    			}
    			else
    			{
    				if (sta.size() == 0)
    				{
    					return false;
    				}
    				ch = sta.top();
    				sta.pop();
    				switch (*iter)
    				{
    				case ')':
    					if (ch != '(')
    					{
    						return false;
    					}
    					break;
    				case '}':
    					if (ch != '{')
    					{
    						return false;
    					}
    					break;
    				case ']':
    					if (ch != '[')
    					{
    						return false;
    					}
    					break;
    				}
    			}
    		}
    		if (sta.size() != 0)
    		{
    			return false;
    		}
    		return true;
    	}
    };
    
    int main()
    {
    	Solution s;
    	cout << s.isValid("[[)") << endl;
    	return 0;
    }


    Keep it simple!
    作者:N3verL4nd
    知识共享,欢迎转载。
  • 相关阅读:
    POJ2983Is the Information Reliable
    POJ2706Connect
    POJ1716Integer Intervals
    js Number 转为 百分比
    c# Unicode编码
    json datatable
    分割js 数组
    IQueryable定义一个扩展方法。分页
    sql 计算岁数
    sql 获取一个周的周一和周日
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/6616319.html
Copyright © 2020-2023  润新知