leetcode 32 最長有效括號
阿新 • • 發佈:2019-01-30
給定一個只包含 '('
和 ')'
的字串,找出最長的包含有效括號的子串的長度。
示例 1:
輸入: "(()"
輸出: 2
解釋: 最長有效括號子串為 "()"
示例 2:
輸入: ")()())
" 輸出: 4 解釋: 最長有效括號子串為"()()"
思路:
開闢一個與輸入string等長新的陣列match,初始化為0;
開闢一個棧,用來匹配有效括號。
若匹配成功,則把match陣列中與匹配成功的括號位置的數變為count,count表示這是第幾對匹配成功的括號。
匹配完成後,遍歷match陣列,找出不含0的最長子集長度。
舉例:
輸入string s = “()(()”
初始化match[5] = {0,0,0,0,0};
然後進行括號匹配,一共兩對匹配括號,故更新後的match陣列為{1,1,0,2,2}
最長子串長度為2,故最終結果為2.
class Solution { public: int longestValidParentheses(string s) { stack<char> list; int len = 0; int count = 1; vector<int> index; vector<int> match; if(s.length() == 0) return 0; list.push(s[0]); index.push_back(0); for(int i = 0; i < s.length(); i++) { match.push_back(0); } for(int i = 1; i < s.length(); i++) { if(!list.empty()) if(isMatch(list.top(), s[i])) { list.pop(); match[i] = count; match[index.back()] = count; count++; index.pop_back(); } else { list.push(s[i]); index.push_back(i); } else { list.push(s[i]); index.push_back(i); } } len = result(match); return len; } int result(vector<int> vec){ int len = vec.size(); int max = 0; int cur = 0; for(int i = 0; i < len; i++) { if(vec[i] == 0) { max = max> cur? max:cur; cur = 0; } else cur++; } max = max> cur? max:cur; return max; } bool isMatch(char s1, char s2){ if(s1 == '(' && s2 == ')') return true; else return false; } };