码迷,mamicode.com
首页 > 其他好文 > 详细

Q1:Valid Parentheses

时间:2014-11-19 10:33:46      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   on   div   

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         else
15             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                     else
30                     {
31                         i -= 1;
32                         j += 1;
33                     }
34                     break;
35                 case ]:
36                     if(stack[i-1] != [)
37                         return false;
38                     else
39                     {
40                         i -= 1;
41                         j += 1;
42                     }
43                     break;
44                 case }:
45                     if(stack[i-1] != {)
46                         return false;
47                     else
48                     {
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

标签:style   blog   io   ar   color   os   sp   on   div   

原文地址:http://www.cnblogs.com/ISeeIC/p/4107427.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!