首页 > 学院 > 开发设计 > 正文

leetcode-Valid Parenthese

2019-11-10 17:48:06
字体:
来源:转载
供稿:网友

括号匹配

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.

Subscribe to see which companies asked this question.

class Solution {public: bool isValid(string s) { char stack[5000]; int top = 0; int len = s.size(); for(int i = 0 ; i < len;i++ ){ if(!top){ stack[top++] = s[i]; } else{ switch(s[i]){ case '(': case '[': case '{':stack[top++] = s[i];break; case ')': if(stack[top-1] == '('){ top--; } else{ return false; } break; case ']': if(stack[top-1] == '['){ top--; } else{ return false; } break; case '}': if(stack[top-1] == '{'){ top--; } else{ return false; } break; default:break; } } } if(top == 0){ return true; } return false; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表