前言
给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。
示例 1: 输入: "(()" 输出: 2 解释: 最长有效括号子串为 "()"
示例 2:
输入: ")()())" 输出: 4 解释: 最长有效括号子串为 "()()"
Code
#! /usr/bin/python3
# -*- coding:utf-8 -*-
# file: leetcode1.py
# author: wangchenxi
# mail: wongchenxi@icloud.com
# brief:
# version: 0.1.00
# Create Time:2019-12-22 19:39:36
# Last Update: 2019-12-22 19时58分23秒
res = 0
b_start = False
expact_num = 0
tmp_len = 0
real_len = 0
s = input('Please input a string:')
for c in s :
if not b_start and c == '(':
b_start = True
expact_num += 1
tmp_len += 1
elif not b_start:
continue
elif b_start and c == '(':
expact_num += 1
tmp_len += 1
elif b_start and c == ')' and expact_num > 0:
expact_num -= 1
tmp_len += 1
real_len = tmp_len
res = res if res > real_len else real_len
elif b_start and c == ')':
res = res if res > real_len else real_len
b_start = False
tmp_len = 0
real_len = 0
expact_num = 0
elif b_start:
tmp_len += 1
print(res)
版权声明:除特别注明外,本站所有文章均为王晨曦个人站点原创