LeetCode解题笔记 - 3. Longest Substring Without Repeating Characters

Posted liyan.web

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode解题笔记 - 3. 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.

给定一个字符串,找到最长的子串的长度没有重复字符。

 

这题其实思路就是把字符串中的字符遍历,记录每个字符的位置,遇到相同的字符更新位置,然后比较长度。可是自己做的乱七八糟,多出很多没用的东西。

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    var count = 0,//本来想用来记录当前连续无重复字符数,但其实不需要,i-start+1就等于它
        obj = {},
        arr = s.split(‘‘),
        start = 0,
        length = 0,
        del = "",//本来想用来记录,然后删除重复字符之前的,没用了的字符,但其实完全没必要,只需要记录历史以前最长长度length和当前无重复字符开始位置start就可以
        Substring = "";//审题不仔细,本来以为要返回子字符串的
    for(var i=0;i<arr.length;i++){
        //debugger;
        if(obj[arr[i]] === undefined){
        }else{
            start = obj[arr[i]] + 1;

        }
            if(i-start+1 > length){
                Substring = s.slice(start,i+1);
            }
            obj[arr[i]] = i;
    }
    return length;
};

然后对比热门答案,真是无地自容,解题方法没想到都还算了,本质思路其实不差多少,却多出来那么多垃圾代码。以后要注意审视自己写的东西了

   public int lengthOfLongestSubstring(String s) {
        if (s.length()==0) return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max=0;
        for (int i=0, j=0; i<s.length(); ++i){
            if (map.containsKey(s.charAt(i))){
                j = Math.max(j,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-j+1);
        }
        return max;
    }
技术分享图片
var lengthOfLongestSubstring = function(s) {
    var obj = {},
        arr = s.split(‘‘),
        start = 0,
        length = 0;
    for (var i = 0; i < arr.length; i++) {
        if (obj.hasOwnProperty(arr[i])) {
            start = obj[arr[i]] + 1;
        }
        obj[arr[i]] = i;
        length = Math.max(length, i - start + 1)
    }
    return length;
};
View Code

 

以上是关于LeetCode解题笔记 - 3. Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode解题报告—— Longest Valid Parentheses

LeetCode 521 Longest Uncommon Subsequence I 解题报告

leetcode : Longest Substring Without Repeating Characters 解题报告

LeetCode 3. Longest Substring Without Repeating Characters

LeetCode 3. Longest Substring Without Repeating Characters

LeetCode 128. 最长连续序列(Longest Consecutive Sequence)