標籤:c c++ java python leetcode
Problem:
Given a string containing just the characters ‘(‘ and ‘)‘, find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
Solution:維持一個字元棧和位置棧,字元棧記錄沒有匹配的字元,位置棧記錄每一個入棧的字元的位置,如果入棧的是右括弧,並且棧頂為左括弧,則退棧,求出當前連續退棧的字元長度,求出這個最大值就是。
題目大意:給一個字串,只包含左括弧和右括弧,求出這個字串合法括弧的最大長度。
Java原始碼(350ms):
public class Solution { public int longestValidParentheses(String s) { int len=s.length(),max=0; Stack<Character> str_stack = new Stack<Character>(); Stack<Integer> pos_stack = new Stack<Integer>(); char[] str=s.toCharArray(); for(int i=0;i<len;i++){ if(str[i]=='('){ str_stack.push('('); pos_stack.push(i); }else{ if(str_stack.size()>0 && str_stack.peek().equals('(')){ str_stack.pop(); pos_stack.pop(); int tmp=pos_stack.size()==0?i+1:i-pos_stack.peek(); max=Math.max(max,tmp); }else{ str_stack.push(')'); pos_stack.push(i); } } } return max; }}
C語言原始碼(3ms):
int longestValidParentheses(char* s) { int len=strlen(s),max=0,top=0,i,tmp; int* pos_stack=(int*)malloc(sizeof(int)*len); char* str_stack=(char*)malloc(sizeof(char)*len); for(i=0;s[i];i++){ if(s[i]=='('){ str_stack[top]='('; pos_stack[top]=i; top++; }else{ if(str_stack[top-1]=='('){ top--; if(top==0)tmp=i+1; else tmp=i-pos_stack[top-1]; max=max>tmp?max:tmp; }else{ str_stack[top]=')'; pos_stack[top]=i; top++; } } } return max;}
C++原始碼(7ms):
class Solution {public: int longestValidParentheses(string s) { int max=0,top=0,len=s.size(); int* pos_stack=(int*)malloc(sizeof(int)*len); char* str_stack=(char*)malloc(sizeof(char)*len); for(int i=0;i<len;i++){ if(s[i]=='('){ str_stack[top]='('; pos_stack[top]=i; top++; }else{ if(str_stack[top-1]=='('){ int tmp; top--; if(top==0)tmp=i+1; else tmp=i-pos_stack[top-1]; max=max>tmp?max:tmp; }else{ str_stack[top]=')'; pos_stack[top]=i; top++; } } } return max; }};
Python原始碼(105ms):
class Solution: # @param {string} s # @return {integer} def longestValidParentheses(self, s): length=len(s);top=0;Max=0 str_stack=[' ' for i in range(length)] pos_stack=[0 for i in range(length)] for i in range(length): if s[i]=='(': str_stack[top]='(' pos_stack[top]=i top+=1 else: if top>0 and str_stack[top-1]=='(': top-=1 tmp=i+1 if top==0 else i-pos_stack[top-1] Max=Max if Max>tmp else tmp else: str_stack[top]=')' pos_stack[top]=i top+=1 return Max
LeetCode 32 Longest Valid Parentheses (C,C++,Java,Python)