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; };