【LeetCode】最长括号匹配Longest Valid Parentheses

来源:互联网 发布:java注解用处 编辑:程序博客网 时间:2024/05/21 01:54

Longest Valid Parentheses [ 最长括号匹配 ]
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.

(1)C++

#include "stdafx.h"#include <iostream>#include <stack>#include <algorithm>    //max()函数//#include <math.h>using namespace std;int GetLongestParenthese(const char* p) {    int size = (int)strlen(p);    stack<int> s;    int start = -1; //将起点设为-1 这样计算最长匹配长度时,只需end - start即可!    int answer = 0; //最终解    for (int i = 0; i < size; i++) {        if (p[i] == '(') {            s.push(i);  //因为入栈的一定是左括号,故没必要将其本身入栈,应将当前遍历字符的 索引 入栈!        }        else {  //p[i] == ')'            if (s.empty()) {    //说明此时没有左括号与之匹配。将该点(i)设为计数起点(start)。 类似之前start = -1的思想。                start = i;            }            else {  //说明栈s中有与之匹配的左括号                s.pop();    //见到一个匹配 就将其弹栈                if (s.empty()) {    //说明此时栈空:不再有左括号与当前遍历元素匹配。-> 比较answer(当前最大长度)与i-start的长短,更新answer。                    answer = max(answer, i - start);  //answer = answer >= (i - start) ? answer : i - start;                }                else {  //说明弹出后,栈s中依然有尚未匹配的左括号。-> 比较answer(当前最大长度)与i-s.top()的长短,更新answer。                    answer = max(answer, i - start);                }            }        }    }    return answer;}int main(){    char* ch = "()())((())())";    int num = GetLongestParenthese(ch);    cout << num << endl;    return 0;}

(2)Java

1)Javapublic class Solution {    public int longestValidParentheses(String s) {        if (s == null) {            return 0;        }        Stack<Integer> stack = new Stack<Integer>();        int maxLen = 0;        int accumulatedLen = 0;        for(int i = 0; i < s.length(); i++) {            if (s.charAt(i) == '(') {                stack.push(i);            } else {                if (stack.isEmpty()) {                    accumulatedLen = 0;                } else {                    int matchedPos = stack.pop();                    int matchedLen = i - matchedPos + 1;                    if (stack.isEmpty()) {                        accumulatedLen += matchedLen;                        matchedLen = accumulatedLen;                    } else {                        matchedLen = i - stack.peek();                    }                    maxLen = Math.max(maxLen, matchedLen);                }            }        }        return maxLen;   }}

【挑战】
可否将空间复杂度由O(N)降至O(1)?
(mark)

阅读全文
1 0
原创粉丝点击