美文网首页
(leetcode) Longest Substring Wit

(leetcode) Longest Substring Wit

作者: 李云轩 | 来源:发表于2016-05-17 23:25 被阅读0次

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) Longest Substring Wit

      本文链接:https://www.haomeiwen.com/subject/vkairttx.html