|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
输入:s = ")()())"
输出:4
解释:最长有效括号子串是 "()()"
'-------------------------------------------------------
Sub Solution()
Dim s As String
s = ")()(()))"
MsgBox longestValidParentheses(s)
End Sub
Function longestValidParentheses(s As String) As Integer
Dim ans, n, i, l, r
ans = 0: n = Len(s)
If n = 0 Then longestValidParentheses = 0: Exit Function
l = 0: r = 0
For i = 1 To n
If Mid(s, i, 1) = "(" Then
l = l + 1
Else
r = r + 1
End If
If l = r Then
ans = Application.Max(ans, 2 * r)
Else
If r > l Then
l = 0: r = 0
End If
End If
Next
l = 0: r = 0
For i = n To 1 Step -1
If Mid(s, i, 1) = "(" Then
l = l + 1
Else
r = r + 1
End If
If l = r Then
ans = Application.Max(ans, 2 * r)
Else
If l > r Then
l = 0: r = 0
End If
End If
Next
longestValidParentheses = ans
End Function
请问:怎么证明该方法是正确的?
谢谢!
|
|