首页 > 代码库 > Q1:Valid Parentheses
Q1:Valid Parentheses
Question:
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.
MyAnswer 1:
1 class Solution { 2 public: 3 bool isValid(string s) { 4 char stack[s.size()]; 5 int i = 0; 6 int j = 0; 7 8 //cout << s; 9 10 if(s[j] == ‘)‘ || s[j] == ‘]‘ || s[j] ==‘}‘)11 return false;12 else if(s[j] == ‘\0‘)13 return true;14 else15 stack[i++] = s[j++];16 17 while(1)18 {19 switch(s[j])20 {21 case ‘\0‘:22 if(i == 0)23 return true;24 else 25 return false;26 case ‘)‘:27 if(stack[i-1] != ‘(‘)28 return false;29 else30 {31 i -= 1;32 j += 1;33 }34 break;35 case ‘]‘:36 if(stack[i-1] != ‘[‘)37 return false;38 else39 {40 i -= 1;41 j += 1;42 }43 break;44 case ‘}‘:45 if(stack[i-1] != ‘{‘)46 return false;47 else48 {49 i -= 1;50 j += 1;51 }52 break;53 default:54 stack[i++] = s[j++];55 break;56 }57 }58 }59 };
数组模拟栈,匹配到括号则出栈,否则入栈
Q1:Valid Parentheses
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。