O(sumof(n)) 时间复杂度
O(sumof(n)) time complexity
问题简单明了:有没有时间复杂度
这是正确的写法吗?
我问是因为我写的这个程序:
def check(self, front, s, back):
if(s[front:back] == s[front:back][::-1]):
return s[front:back]
else:
return self.check(front, s, back-1)
def checkIter(self, front, s, back, longest):
r = self.check(front, s, back)
if(len(r) >= len(longest)): longest = r
if(front < back):
return self.checkIter(front+1,s,back, longest)
else:
return longest
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
return self.checkIter(0,s,len(s),"")
在 longestPalindrome('cbbd')
的输入上它运行 ~10 次产生输出:
"cbbd" "cbb" "cb" "c" "bbd" "bb" "b" "bd" "b" "d"
。在 longestPalindrome('cbbda')
的类似输入上给出:
"cbbda" "cbbd" "cbb" "cb" "c" "bbda" "bbd" "bb" "b" "bda" "bd" "b" "da" "d" "a"
所以这不可能是 O(n)
指定的总和等于n(n+1)/2
。因此,它在 O(n^2)
.
问题简单明了:有没有时间复杂度
这是正确的写法吗? 我问是因为我写的这个程序:
def check(self, front, s, back):
if(s[front:back] == s[front:back][::-1]):
return s[front:back]
else:
return self.check(front, s, back-1)
def checkIter(self, front, s, back, longest):
r = self.check(front, s, back)
if(len(r) >= len(longest)): longest = r
if(front < back):
return self.checkIter(front+1,s,back, longest)
else:
return longest
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
return self.checkIter(0,s,len(s),"")
在 longestPalindrome('cbbd')
的输入上它运行 ~10 次产生输出:
"cbbd" "cbb" "cb" "c" "bbd" "bb" "b" "bd" "b" "d"
。在 longestPalindrome('cbbda')
的类似输入上给出:
"cbbda" "cbbd" "cbb" "cb" "c" "bbda" "bbd" "bb" "b" "bda" "bd" "b" "da" "d" "a"
所以这不可能是 O(n)
指定的总和等于n(n+1)/2
。因此,它在 O(n^2)
.