码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode经典试题:Longest Substring Without Repeating Characters解析

时间:2019-03-06 09:20:37      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:判断   poi   item   star   其他   one   pos   lines   length   

题目如下:

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解析

标签:判断   poi   item   star   其他   one   pos   lines   length   

原文地址:https://www.cnblogs.com/jiading/p/10480876.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!