|
亲!马上注册或者登录会查看更多内容!
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
题目(一):Count and Say
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
题目(二):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.
图片割开参考答案:
题目(一): 题目(二):


python参考解答:
题目(一):Count and Say
[code]class Solution:
# @return a string
def count(self,s):
t=''; count=0; curr='#'
for i in s:
if i!=curr:
if curr!='#':
t+=str(count)+curr
curr=i
count=1
else:
count+=1
t+=str(count)+curr
return t
def countAndSay(self, n):
s='1'
for i in range(2,n+1):
s=self.count(s)
return s[/code]
题目(二):Longest Valid Parentheses
[code]class Solution:
# @param s, a string
# @return an integer
def longestValidParentheses(self, s):
maxlen = 0
stack = []
last = -1
for i in range(len(s)):
if s【i】=='(':
stack.append(i) # push the INDEX into the stack!!!!
else:
if stack == []:
last = i
else:
stack.pop()
if stack == []:
maxlen = max(maxlen, i-last)
else:
maxlen = max(maxlen, i-stack[len(stack)-1])
return maxlen[/code]
|
|