leetCode #20 Valid Parentheses

来源:互联网 发布:中国环保网络电视台 编辑:程序博客网 时间:2024/04/29 23:18

题目:判断各种括号是否正确匹配

分析:用栈来解决,左边的括号push进去,右边的括号则判断是否在栈顶有对应的左括号。

还有一种方法是搜索字符串,有效的字符串里必定有一组括号是相邻且匹配的。

答案:

class Solution {
public:
 bool isValid(string s) {
  int len = s.length();
  stack<char> stk;
  bool result = true;
  for (int i = 0; i < len; i++)
  {
   if (s[i] == '(' || s[i] == '[' || s[i] == '{')
    stk.push(s[i]);
   else
   {
    if (s[i] == ')')
    {
     if (!stk.empty() && stk.top() == '(')
      stk.pop();
     else
     {
      result = false;
      break;
     }

    }

    if (s[i] == ']')
    {
     if (!stk.empty() && stk.top() == '[')
      stk.pop();
     else
     {
      result = false;
      break;
     }
    }

    if (s[i] == '}')
    {
     if (!stk.empty() && stk.top() == '{')
      stk.pop();
     else
     {
      result = false;
      break;
     }
    }

   }

  }

  if (!stk.empty())
   result = false;
  
  return result;

 }
};


0 0
原创粉丝点击