日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode——Longest Substring Without Repeating Characters

發(fā)布時(shí)間:2025/4/16 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。