leetcode第3题——**Longest Substring Without Repeating Characters

25 篇文章 0 订阅
25 篇文章 0 订阅

题目

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

思路

从左向右遍历字符串并作为子串,创建一个字典存储当前子串中各个字符的个数,当判断当前子串有重复的字符时,子串向右滑动1位,即遍历开头的位置加1。以输入字符串'edvldf'为例:当遍历到第2个d时向右滑动1位,从第一个d开始遍历,并且“被滑掉”的字符的个数要减1,取当前子串的长度(遍历下标减去开始位置再加1就是)存入结果res中;然后从第一个d开始遍历又到第二个d时向右滑动1位,从v开始遍历,以此循环一直到遍历完整个字符串。最后返回子串长度的最大值。

代码

Python

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        start = 0
        end = 1
        res = end - start
        count_dic = {}
        for letter in s:
            count_dic[letter] = count_dic.get(letter,0) + 1#如果字典已经含当前字符则个数加1,否则其个数为1
            while count_dic.get(letter) > 1:
                count_dic[s[start]] -= 1
                start += 1
            res = max(res,end - start)
            end += 1
        return res
Java
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int start = 0;
        int end = 1;
        int res;
        if(s.length() == 0)
            return 0;
        else
            res = end - start;

        Map<Character,Integer> map = new HashMap<Character,Integer>();
        
        for(int i = 0;i < s.length();i++)
            map.put(s.charAt(i),0);
        
        for(int i = 0;i < s.length();i++)
        {
            map.put(s.charAt(i),map.get(s.charAt(i)) + 1);
            //while循环实现子字符串往右滑动
            while(map.get(s.charAt(i)) > 1)
            {
                map.put(s.charAt(start),map.get(s.charAt(start)) - 1);
                start += 1;
            }
            if(end - start > res)
                res = end - start;
            end++;
        }
        return res;
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值