前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode Longest Substring Without Repeating Characters

LeetCode Longest Substring Without Repeating Characters

作者头像
发布2018-09-04 11:38:25
3430
发布2018-09-04 11:38:25
举报
文章被收录于专栏:WD学习记录

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 subsequenceand not a substring.

解法1: 参考自LeetCode题解3:Longest Substring Without Repeating Characters

代码语言:javascript
复制
class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        start=0
        max_length=0
        n=len(s)
        sub_str=''
        for end in range(n):
            if s[end] not in sub_str:
                sub_str+=s[end]
            else:
                max_length=max(max_length,len(sub_str))
                while s[start]!=s[end]:
                    start+=1
                start+=1
                sub_str=s[start:end+1]
        return max(max_length,len(sub_str))

解法2: 参考自LeetCode该题目提交中 sample 64 ms submission

代码语言:javascript
复制
class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        chars = {}
        begin = 0
        result = 0
        for i, c in enumerate(s, 1):
            if (c in chars) and (chars[c] > begin):
                begin = chars[c]
            elif (i - begin > result):
                result = i - begin              
            chars[c] = i
        return result
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018年08月05日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档