ValidParentheses

  

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true

解题思路:一开始想的比较简单,想在数组开头a[0]和数组结尾a[''],作比较,如果头和尾相同,就判断为True,结果发现出错了,后来看下,是写一个栈就可以,碰到(,{,[,就入栈,遇到),},],就出栈,如果匹配则是True,如果不匹配或栈内还有其他元素,则是False。
 1 bool isValid(char* s){
 2     int len =  strlen(s);
 3     if(len%2) return false;
 4     
 5     int limit = len/2;
 6     char *stack = malloc(limit);
 7     int idx = 0;
 8     
 9     for(int i = 0; i<len; i++){
10         char cur = s[i];
11         if(cur == '(' || cur=='{' || cur =='['){
12             if(idx == limit) return false;
13             stack[idx++] = cur;
14         }
15         else
16         {
17             if(idx == 0) return false;
18             if(cur == '}' && stack[idx-1] == '{' || cur == ']' && stack[idx-1] == '[' || cur == ')' && stack[idx-1] == '('){
19                 idx--;                
20             }
21             else
22             {
23                 return false;
24             }
25         }
26     }
27     free(stack);
28     return idx == 0;
29 }
原文地址:https://www.cnblogs.com/WuLiang-cola/p/9167577.html