您的位置:首页 > 其它

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

2015-12-19 22:56 429 查看

题目

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;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: