leetcode03_Longest Substring Without Repeating Characters

一.问题描述

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.




二.编写代码

1.输入:字符串

2.输出:最长不重复子串的长度

代码如下:

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        len_s=len(s)
        #处理特殊情况:s为空字符串
        if len_s==0:
            return 0
        max_len=1
        #两个指针初始化
        i=0
        j=1
        while (j<len_s):
            while (s[i:j].find(s[j])<0): 
                #j指针前面没有与j指向的字符相同的
                j=j+1
                if j>=len_s:
                    break
            if max_len<j-i:
                max_len=j-i
            if j<len_s:
                i=s[i:j].find(s[j])+1+i
        return max_len

算法效率不错,如下图:


三.算法思想

通过使用两个指针i,j,初始化i=0,j=1。通过使j向右移动直至当前j所指向的字符与子串s[i:j]中某个字符重复,此时j-i即为一个不重复的子串,之后i重新赋值为当前子串相同字符的后一位,j再右移寻找新的不重复子串。该循环的过程中不断比较得出最长的不重复子串的长度。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值