使用递归解决方案尝试this:
递归地我正在创建所有子串并检查它是否是回文。
问题是我想摆脱全局变量 count 。
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
def palin(s):
if s == s[::-1]:
return True
return False
global count
count = 0
def helper(s, cur, dp):
global count
ret = 0
if cur >= len(s)-1:
return 0
if cur in dp:
return
for i in range(cur+1, len(s)):
if palin(s[cur:i+1]):
count += 1
ret = helper(s, i, dp)
else:
ret = helper(s, i, dp)
dp[cur] = ret
helper(s, 0, {})
return count + len(s)
到目前为止我尝试过:
def helper(s, cur, dp, count):
ret = 0
if cur >= len(s)-1:
return count
if cur in dp:
return dp[cur]
for i in range(cur+1, len(s)):
if palin(s[cur:i+1]):
ret = helper(s, i, dp, count + 1)
else:
ret = helper(s, i, dp, count)
dp[cur] = ret
return dp[cur]
答案 0 :(得分:0)
只需在递归count
函数中传递helper
变量(并根据需要增加)。
答案 1 :(得分:0)
您可以创建一个新的Counter类来跟踪您的计数
class Counter:
def __init__(self):
self.count = 0
def __add__(self,num):
self.count+=num
return self
然后修改您的代码以使用该计数器
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
def palin(s):
if s == s[::-1]:
return True
return False
def helper(s, cur, dp,count): #make a parameter for Counter
ret = 0
if cur >= len(s)-1:
return 0
if cur in dp:
return
for i in range(cur+1, len(s)):
if palin(s[cur:i+1]):
count+=1
ret = helper(s, i, dp,count) #pass in the Counter
else:
ret = helper(s, i, dp,count) #pass in here as well
dp[cur] = ret
a = Counter() #Change here
helper(s, 0, {},a) #Change here
return a.count + len(s) #Change here
您设计计数和递归的方式,您别无选择,只能使用可变对象来跟踪计数。当然,还有更好的方法可以解决这个问题。
答案 2 :(得分:0)
这是一个尽可能多的递归版本(包括你的palin
drome函数):
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
def palin(s):
"""recursively checks if bookends match on narrower substrings"""
if len(s) <= 1:
return True
else:
# checks if bookends match and inner substring is a palindrome
return (s[0] == s[-1]) & palin(s[1:-1])
def first_char_palin_count(s):
"""counts palindromes of all substrings with first char (pos 0)
e.g. will check: "abba", "abb", "ab", "a", "" in palin()
"""
if len(s) <= 0:
return 0
# if s is palindrome + shorter palindromes with first char
else:
return palin(s) + first_char_palin_count(s[:-1])
def helper(s):
"""counts palindromes in all substrings"""
if len(s) <= 0:
return 0
else:
# first char palindromes + palindromes not including first char
return first_char_palin_count(s) + helper(s[1:])
return helper(s)
注意:
helper
匹配你的)来处理所有子串(有和没有第一个字符)