本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

LeetCode: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.                 本文地址


简单的括号匹配问题,用栈来解决                                        

复制代码
 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         int n = s.size();
 5         if(n == 0)return true;
 6         stack<char> sta;
 7         sta.push('#');
 8         for(int i = 0; i < n; i++)
 9         {
10             switch(s[i])
11             {
12                 case '(': sta.push('('); break;
13                 case '{': sta.push('{'); break;
14                 case '[': sta.push('['); break;
15                 case ')': {
16                     char top = sta.top();
17                     if(top != '(')return false;
18                     else sta.pop();
19                     break;}
20                 case '}': {
21                     char top = sta.top();
22                     if(top != '{')return false;
23                     else sta.pop();
24                     break;}
25                 case ']': {
26                     char top = sta.top();
27                     if(top != '[')return false;
28                     else sta.pop();
29                     break;}
30             }
31         }
32         if(sta.size() == 1)return true;
33         else return false;
34     }
35 };
复制代码

 

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3776395.html

 

posted @   tenos  阅读(595)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架

本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

公益页面-寻找遗失儿童

点击右上角即可分享
微信分享提示