>> >> >> Reference << << << <<<<<<Ref>>>>>>
>> >> >> Indexer << << << <<<<<<Idx>>>>>>
Matched: 0

Tags

    Categories

      Types

        Top Results

          LC20.ValidParentheses
          M: 2026-04-27 - ljf12825

          题目

          有效的括号
          给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
          有效字符串需满足:
          左括号必须用相同类型的右括号闭合。
          左括号必须以正确的顺序闭合。
          每个右括号都有一个对应的相同类型的左括号。
          

          题解

          #include <iostream>
          #include <stack>
          #include <unordered_map>
          #include <string>
          
          class Solution
          {
          public:
          	bool isValid(std::string s)
          	{
          		if (s.size() % 2 != 0) return false;
          		std::unordered_map<char, char> table =
          		{
          			{')', '('}, {']', '['}, {'}', '{'}
          		};
          
          		std::stack<char> stk;
          		for (char ch : s)
          		{
          			if (table.count(ch))
          			{
          				if (stk.empty() || stk.top() != table[ch]) return false;
          				stk.pop();
          			}
          			else stk.push(ch);
          		}
          		return stk.empty();
          	}
          
          };