(LeetCode) 32。最长有效括号

  

给定一个字符串只包含characters  <代码> '('> ')'>

For  <代码>”(()"> " ()">

另一个例子is  <代码>”)()())" ,最长有效括号substring is  <代码>”()()>

1)创建栈,碰到匹配的括号时,弹出栈顶元素,否则,。

2)创建数组,当出栈动作发生时,把到目前为止的入栈次数与出栈次数的差值存入数组中。

3)数组处理。获取最长字串。


)字符串模式   ),(()),),((())),,对应数组为:3,2,5,4,3      B)字符串模式   ),()(),),()()(),,对应数组为:2,2,3,3,3      C)字符串模式   ),(),),(),((())),对应数组为:2,3,5,4,3      D)字符串模式   ),(()),),(())(),,对应数组为:3,2,4,3,3      由上可知:   模式匹配基本就只有   1、嵌套(())   2、平级()()      第一种方式的数组会出现递减方式,第二种方式的数组元素会出现保持不变的。      一旦出现不匹配的,那么只有推动作存在,遇到流行时中间push和pop的差肯定是增涨的。可是如果中间都是匹配的,那么最终push和pop的差不会涨。      获取最长字串的方法:   获取递减序列,纪录递减序列长度,并纪录递减序列开始的首元素和尾元素。从纪录的首元素开始往前查找,直到遇到的元素小于纪录的尾元素,记前驱长度。   递减序列长度+前驱长度,=,字串长度。



struct 堆栈   {   ,,,char 词;   ,,,struct  stack  *下;   };      struct 堆栈   *推(struct  stack  *头,,char 词)   {   ,,,struct  stack  * node =, (struct  stack  *) malloc (sizeof (struct 堆栈));   ,,,if  (, node  !)   ,,,{   ,,,,,,,printf (" create  node 错误\ n ");   ,,,,,,,return 头;   ,,,}   ,,,,   ,,,节点→word =,词;   ,,,if  (, head  !)   ,,,{   ,,,,,,,节点→next =,空;   ,,,,,,,head =,节点;   ,,,}   ,,,   ,,,{   ,,,,,,,节点→next =,头;   ,,,}   ,,,,   ,,,return 节点;   }      struct 堆栈   流行(struct  stack  * *头)   {   ,,,if  (, head  !)   ,,,{   ,,,,,,,return 头;   ,,,}   ,,,,   ,,,struct  stack  * del =,头;   ,,,head =,头→下;   ,,,自由(del);   ,,,,   ,,,return 头;   }      字符   顶部(struct  stack  *头)   {   ,,,if  (, head  !)   ,,,{   ,,,,,,,return  0;   ,,,}   ,,,,   ,,,return 头→词;   }      无效   stackFree (struct  stack  *头)   {   ,,,if  (, head  !)   ,,,{   ,,,,,,,返回;   ,,,}   ,,,,   ,,,struct  stack  * del =,空;   ,,,while  (, head )   ,,,{   ,,,,,,,del =,头;   ,,,,,,,head =,头→下;   ,,,,,,,自由(del);   ,,,}   }      int   longestValidParentheses (char *, s)   {   ,,,if  (, s  !)   ,,,{   ,,,,,,,return  0;   ,,,}   ,,,,   ,,,int  size =, strlen (s),/, 2, +, 1;   ,,,int 子(大小);   ,,,int  index =, 0;   ,,,struct  stack  * head =,空;   ,,,int  pushNum =, 0;   ,,,int  popNum ,=, 0;   ,,,int  flag =, 0;   ,,,for (,, *年代;,s + +,)   ,,,{,,   ,,,,,,,if  (==,, * s  ' (',)   ,,,,,,,{,,   ,,,,,,,,,,,head =,推动(头,,* s);   ,,,,,,,,,,,pushNum  +=, 1;   ,,,,,,,,,,,flag =, 0;   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

(LeetCode) 32。最长有效括号