原题目摘自leetcode网站
Longest Substring Without Repeating Characters
题目:
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
Subscribe to see which companies asked this question.
简单翻译意思就是在一个长字符串中找出最长的子字符串,并且子字符串中不能包含重复的元素。
一开始尝试了最简单暴力的方法,一次循环把所有子字符串都找出来存到了一个列表,再循环一遍找最长的。该方法在最后的测试样例中因为超过时间fail了,纠结了很久。
然后重新想想问题,找最长的子串并输出,其实就是遍历该字符串,找出两个相同元素之间最长的一个序列,一个循环就能搞定。
贪心算法先声明一个变量存遍历到上一元素位置没有重复的子串,在声明一个变量存当前最长子串的长度,每次遍历新字符的时候检查是否在第一个变量子串里出现,不出现则判断一下目前子串的长度与最长子串的长度谁大;如果元素在目前子串出现了,则把第一个变量更新成去掉重复字符及之前部分的子串加上新的字符。一次循环下来就可得出答案。
以下是代码:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
elif len(s) == 1:
return 1
max_len = 0
sub_str = ''
for ss in s:
if ss not in sub_str:
sub_str += ss
if max_len < len(sub_str):
max_len = len(sub_str)
else:
if ss != sub_str[-1]:
idx = sub_str.index(ss)
sub_str = sub_str[idx+1:]+ss
else:
sub_str = ss
return max_len
if __name__ == '__main__':
sol = Solution()
print sol.lengthOfLongestSubstring('pwwkew')