更新时间:2018-02-21 10:58:33浏览次数:1+次
我在leetcode上找到一题最长子序列的:
代码测试:
code:
class Solution:
def lengthOfLongestSubstring(self, s):
position = [] # 标记不重复的字符列表
char_distance = 0 # 第i 个字符与该字符上一次出现的距离
maxLength = 0 # 存储最长子序列
for index, x in enumerate(s):
if x not in position:
position.append(x)
else:
char_distance = len(position) - position.index(x) # 计算距离
if char_distance <= len(position):
position = position[position.index(x) + 1 :]
position.append(x)
else:
position.append(x)
if len(position) > maxLength:
maxLength = len(position) # 找到最长的子序列, abcabcbb测试案例
return maxLength
if __name__ == "__main__":
s = 'arabcacfr'
ss = Solution()
print(ss.lengthOfLongestSubstring(s))
相关资讯