LeetCode032 Longest Valid Parentheses

详细见:leetcode.com/problems/longest-valid-parentheses


Java Solution: github

package leetcode;

import java.util.Stack;


public class P032_LongestValidParentheses {

	/*
	 * 	TLE
	 * 	对全"("的长字符串,时间超出
	 * 	又是一次艰难AC的过程
	 * 	11 ms
	 * 	22.39%
	 */
	static class Solution1 {
	    public int longestValidParentheses(String s) {
	    	if (s == null)
	    		return 0;
	    	boolean[] isMatch = new boolean[s.length()];
	    	Stack<Integer> stack = new Stack<Integer>();
	    	int ans = 0, i = 0, cou = 0, left = 0, right = 0;
	    	for (i = 0; i != isMatch.length; i ++) {
	    		if (s.charAt(i) == '(') {
	    			left ++;
	    		} else {
	    			right ++;
	    		}
	    	}
	    	if (right == 0 || left == 0)
	    		return 0;
	    	if ((left - 1) * (right - 1) == 0 && s.charAt(0) == '(')
	    		return 2;
	    	for (i = 0; i != isMatch.length; i ++) {
	    		if (s.charAt(i) == '(') {
	    			stack.add(i);
	    		} else {
	    			if (stack.isEmpty())
	    				continue;
	    			isMatch[i] = true;
	    			isMatch[stack.peek()] = true;
	    			stack.pop();
	    		}
	    	}
	    	for (i = 0; i!= isMatch.length; i ++) {
	    		if(isMatch[i])	++cou;
	    		else	cou = 0;
	    		ans = Math.max(ans, cou);
	    	}
	    	return ans;
	    }
	}
}


C Solution: github

/*
    url: leetcode.com/problems/longest-valid-parentheses/
    9ms 21.28%
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//vc do not need below, leetcode need
#define max(a,b) ((a) > (b) ? (a) : (b))
#define min(a,b) ((a) < (b) ? (a) : (b))

struct stk {
    int val;
    struct stk * pre;
    struct stk * nxt;
};

struct stk * stk_push(struct stk * top, int val) {
    struct stk * t = (struct stk *) malloc(sizeof(struct stk));
    t->val = val;
    t->pre = top;
    t->nxt = NULL;
    if (top != NULL) top->nxt = t;
    return t;
};

struct stk * stk_pop(struct stk * top) {
    struct stk * t = top == NULL ? NULL : top->pre;
    if (top == NULL) return NULL;
    if (t != NULL) t->nxt = NULL;
    free(top);
    return t;
};

void stk_free(struct stk * top) {
    struct stk * t = NULL;
    while (top != NULL) {
        t = top->pre;
        free(top);
        top = t;
    }
}

int longestValidParentheses(char* s) {
    int lft = 0, rgt = 0, cnt = 0, ans = 0, i = 0, len = 0;
    struct stk * top = NULL;
    char * m = NULL;
    len = s == NULL ? 0 : strlen(s);
    for (lft = 0, rgt = 0, i = 0; i < len; i ++) {
        if (* (s + i) == '(') lft ++;
        else rgt ++;
    }
    if (lft == 0 || rgt == 0) return 0;
    m = (char *) malloc(sizeof(char) * len);
    memset(m, '\0', len);
    for (i = 0; i < len; i ++) {
        if (*(s + i) == '(') {
            top = stk_push(top, i);
        } else if (top != NULL) {
            *(m + i) = 1;
            *(m + top->val) = 1;
            top = stk_pop(top);
        }
    }
    for (i = 0; i < len; i ++) {
        cnt = *(m + i) == 1 ? cnt+1 : 0;
        ans = max(ans, cnt);
    }
    free(m);
    stk_free(top);
    return ans;
}

int main() {
    char * s = "(())";
    printf("answer is %d\r\n", longestValidParentheses(s));
    return 0;
}


Python Solution: github

#coding=utf-8

'''
    url: leetcode.com/problems/longest-valid-parentheses
    @author:     zxwtry
    @email:      zxwtry@qq.com
    @date:       2017年4月3日
    @details:    Solution: 145ms 13.54%
'''

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        sn = 0 if s == None else len(s)
        if sn == 0: return 0
        stk, ans, cnt = [], 0, 0
        m = [False] * sn
        for i in range(sn):
            if s[i] == '(':
                stk.append(i)
            elif len(stk) != 0:
                m[i] = True
                m[stk.pop()] = True
        for i in range(sn):
            cnt = cnt + 1 if m[i] else 0
            ans = max(ans, cnt)
        return ans

if __name__ == "__main__":
    sol = Solution()
    print(sol.longestValidParentheses(")()())"))



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值