題目:spa
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 hascode
length = 4.orm
大意是尋找字符串裏面 "()"匹配最長的長度。最直接的思路是遍歷字符串,若是是 '(',則判斷下一個字符是不是 ')',若是是,則繼續向下判斷,同時記錄當前最長的字符長度。思路比較直接。時間複雜度:O(n)。blog
int longestValidParentheses(string const& s)//Longest Valid Parentheses { int i=0; int length=s.length();//字符串長度 int long_length=0,max=0; while(i<length)//遍歷字符串 { if(s[i]=='(')//找到前(,判斷後面一個是否爲) { if(s[i+1]==')')//知足 { i=i+2; long_length=long_length+2; if(max<long_length) max=long_length;//記錄字符串長度 } else//不是),繼續查找 { i=i+1; long_length=0; } } else //是),可是不配,過濾 { i=i+1; long_length=0; } } return max; }