LeetCode Algorithms 32. Longest Valid Parentheses

来源:互联网 发布:最好的网络推广公司 编辑:程序博客网 时间:2024/05/22 19:36

题目难度: Hard


原题描述:

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.


题目大意:

        给你一个只包含"("和")"的字符串,让你找出最长的匹配的子串,输出其长度。


解题思路:

        一开始以为是简单的括号匹配,取其中最长的一段匹配的子串就行了。但是后来发现没那么简单,难点在于如何判断当前扫描到的字符是属于之前的一个未匹配完的匹配串的一部分还是新的匹配串的一部分。我在这个问题上想了很久,用代码尝试去实现但是发现始终有测试数据过不了。后来听到了同学的一个方法:用一个数组将匹配的括号的位置标记为true,然后扫描一遍数组,找出连续为true的最大长度,这个就是匹配串的最大长度。


时间复杂度分析:

        算法使用栈来匹配括号,这需要扫描一遍原字符串,时间复杂度为O(n),n为字符串的长度,最后还要扫描一遍记录匹配字符的位置的数组,时间复杂度也是O(n)。因此总的时间复杂度为O(n)。


以下是代码:

class Solution {public:    int longestValidParentheses(string s) {        const int maxLen = 100000;    bool match[maxLen];    memset(match,0,sizeof(match));    stack <char> st1;    stack <int> st2;    int i;    for(i=0 ; s[i]!='\0' ; ++i){        if(s[i]=='('){            st1.push(s[i]);            st2.push(i);        }        else{            if(st1.empty())                continue;            match[i] = true;            match[st2.top()] = true;            st1.pop();            st2.pop();        }    }    int cnt=0;    int ans = 0;    for(i=0 ; i<s.size() ; ++i){        if(match[i]){            ++cnt;        }else{            ans = (ans>cnt ? ans : cnt);            cnt = 0;        }    }    ans = (ans>cnt ? ans : cnt);    return ans;    }};

0 0
原创粉丝点击