1. 程式人生 > >Leetcode經典試題:Longest Substring Without Repeating Characters解析

Leetcode經典試題:Longest Substring Without Repeating Characters解析

long har mea aml clas oos hat 結果 引用

題目如下:

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.
https://leetcode.com/problems/longest-substring-without-repeating-characters/

我學習的優秀代碼:
int lengthOfLongestSubstring(string
s) { vector<int> dict(256, -1); int maxLen = 0, start = -1; for (int i = 0; i != s.length(); i++) { if (dict[s[i]] > start) start = dict[s[i]]; dict[s[i]] = i; maxLen = max(maxLen, i - start); }
return maxLen; }

來源:https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/1737/C%2B%2B-code-in-9-lines.

個人加英文註釋版:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> dict(256,-1);//256 is the amount of ASCII and its expanding. use -1 to initialize,dict stores each letter‘s  index of their last position
        int length=0,start=-1;//initialize
        for(int i=0;i<s.length();i++){// i is the index
            if(dict[s[i]]>start)// it means whether this letter is already contained in the choosed string
                start=dict[s[i]];// if true, the index of start should be reset to the index of the repeated word
            dict[s[i]]=i;//update the index of their last position
            length=max(length,i-start);//i and start both point at the same letter, so the real length is one letter less,i-start-1+1=i-start
        }
        return length;//return the largest length
    }
};

解析如下{

相關知識點{

ASCII碼與拓展ASCII碼{

ASCII 碼使用指定的7 位或8 位二進制數組合來表示128種字符。另外,後128個稱為擴展ASCII碼。許多基於x86的系統都支持使用擴展(或“高”)ASCII。擴展ASCII 碼允許將每個字符的第8 位用於確定附加的128 個特殊符號字符、外來語字母和圖形符號。所以共計256個};

C++ max與min函數的使用{

#include<algorithm>//引用頭文件

min(a,b)或者max(a,b}會返回兩個數中的較小數或者較大數,通常只用於兩個數的大小比較};

};

內容解析{

這個算法最巧妙的地方是使用了哈希表,由於ASCII碼的數量很小,只有256個,並且對應規則很明確(指的是字符和整數的對應規則),所以直接開了一個長度為256的數組做哈希表,用來保存這個字符上一次出現時的下標。由於哈希表的使用,查表的時間復雜度變成了O1級,使得速度的提升非常明顯!這就是哈希表的力量hhhh

在if判斷正確時,i和start指向的都是同樣的字符,所選取的長度應該是要減掉一個的,但是由於尾減去頭的結果會比字符個數少一。所以+1和-1相抵。

其他內容解析見這篇博文:https://www.cnblogs.com/ariel-dreamland/p/8668286.html}

};

Leetcode經典試題:Longest Substring Without Repeating Characters解析