LeetCode——Longest Substring Without Repeating Characters
生活随笔
收集整理的這篇文章主要介紹了
LeetCode——Longest Substring Without Repeating Characters
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
原問題
Given a string, find the length of the?longest substring?without repeating characters.
Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: 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.我的沙雕解法
var lengthOfLongestSubstring = function(s) {let recordObj = {};let length = s.length;let max = 0;for(let i = 0; i < length; i++){let record = 0;for(let g = i; g < length; g++){if(recordObj[s[g]] === undefined){//無重復(fù)字母recordObj[s[g]] = true;record++;}else{//存在重復(fù)字母recordObj = {};break;}}max = record > max? record:max;if(max === length){break;}}return max; };挨打:最暴力的無腦解法,耗時(shí)672ms。。。
貪心解法學(xué)習(xí)
參考了排名較前的答案,多數(shù)是貪心思想,以下摘抄一位的代碼并加上學(xué)習(xí)的注釋
/** * 通過i,j指針計(jì)算子序列長(zhǎng)度 * j指針:表示當(dāng)前循環(huán)的字母,i指針:表示起點(diǎn) * map用于記錄出現(xiàn)過的字母的相鄰下標(biāo),給予i新的起點(diǎn) * 重復(fù)字母出現(xiàn)時(shí),比較當(dāng)前起點(diǎn)與map的記錄位置,取較大值,保證連續(xù)子序列,同時(shí)體現(xiàn)貪心:求 * 當(dāng)前可求得的最長(zhǎng)子序列 **/ var lengthOfLongestSubstring = function(s) {var n = s.length, ans = 0;var map = new Map(); // 記錄出現(xiàn)過字母的相鄰下標(biāo)// try to extend the range [i, j]for (var j = 0, i = 0; j < n; j++) {if (map.has(s.charAt(j))) { //若此字母在之前的循環(huán)中出現(xiàn)過i = Math.max(map.get(s.charAt(j)), i); //保證連續(xù)子序列,同時(shí)體現(xiàn)貪心}ans = Math.max(ans, j - i + 1); //比較map.set(s.charAt(j), j + 1); //記錄字母的相鄰位置}return ans; };此算法耗時(shí)108ms
百度到一張圖片很有利于理解
舉例:qpxrjxkltzyx
圖片來源:https://www.cnblogs.com/wangk...
總結(jié)
以上是生活随笔為你收集整理的LeetCode——Longest Substring Without Repeating Characters的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ECMASCript 2019可能会有哪
- 下一篇: 一地鸡毛 OR 绝地反击,2019年区块