(leetcode) Longest Substring Without Repeating Characters

Question

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.

Solution

First solution

create an ASCII table, the value of that array is the index of the string.

class Solution {
public:
    int k=0, a[128] = { 0 };
    int lengthOfLongestSubstring(string s) {
        int ans = 0,i,j=0;
        for (i = 0; i < s.length(); i++) {
            j = max(a[s[i]],j);            //此处j为最大的重复字符的索引
            ans = max(ans,i-j+1);
            a[s[i]] = i+1;
        }
        return ans;
    }
};  

Second solution

using an unordered_set as a sliding window and let it iterate through the string.

class Solution {
public:
    static int lengthOfLongestSubstring(string s) {
        int ans = 0, i = 0, j = 0;
        unordered_set<char> set;
        for (j; j<(int)s.length();) {
            if (set.count(s[j])<=0) {   //表中不包含字符
                set.insert(s[j++]);        //sliding window 表尾后移
                ans = max(ans, j - i);       
            }
            else {
                set.erase(s[i++]);         //sliding window 表头后移

            }
        }
        return ans;
    }
}; 

Third solution

using an unordered_map as a sliding window and let it iterate through the string.

class Solution
{
public:
    static int lengthOfLongestSubstring(string s) {
        unordered_map<char, int> map;
        int i = 0, j = 0, ans = 0;
        for (; i < (int)s.length(); i++) {
            if (map.find(s[i]) != map.end())
            {
                j = max(j, map[s[i]]);
            }
            ans = max(i - j + 1, ans);
            map.erase(s[i]);
            map.insert({ s[i],i+1 });
            
        }
        return ans;
    }
};

原文地址:我的主页文章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • 终于有点时间整理了前段时间的游记, 不好意思,我的工作时间比较忙, 有空尽量会多整理一些, 不要催我。 行程:瑞典...
    顾小宝阅读 379评论 0 2
  • 云月山川的年华里,给朋友,给自己,给许多牵着我、指引我的人写过随笔,道过感谢。唯有对她, 些许的眷顾也不曾一提,一...
    云角双鱼阅读 480评论 0 0
  • 朋友圈火了, 是你的动态增添了风采, 只是发现你又去欣赏别人的朋友圈总是那么美好, 因为有一种好叫别人家的。 于是...
    沐涟渔阅读 238评论 0 0