算法——Longest Substring Without Repeating Characters

原题目摘自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')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值