3. Longest Substring Without Repeating Characters

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.

method one:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.empty())
            return 0;
        int maxlen=0,start=-1;
        unordered_map<char,int> dict;//存储字符及其下标
        for(int i=0;i<s.size();i++)
        {
            auto it=dict.find(s[i]);
            if(it!=dict.end())
                start=max(start,it->second);//发现重复,更新子串start位置,start取较大值,因为可能发现在start之前出现过的字符
            dict[s[i]]=i;//未重复,加入子串中
            maxlen=max(maxlen,i-start);

        }
        return maxlen;   
    }
};

Method 2:
Don't use hashmap, because the ASCII codes of all characters add up to a maximum of 256. You can directly use an array to replace the hashmap, which is more efficient.
Note: ASCII code occupies one byte and can have a total of 256 values ​​from 0 to 255. The first 128 characters are commonly used characters such as operators, letters, numbers, etc. The last 128 characters that can be displayed on the keyboard are special characters that cannot be found on the keyboard.

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.empty())
            return 0;
        int maxlen=0,start=-1;
        vector<int> dict(256,-1);//存储字符及其下标
        for(int i=0;i<s.size();i++)
        {
            //auto it=dict.find(s[i]);
            if(dict[s[i]]>start)
                start=dict[s[i]];//发现重复,更新子串start位置,start取较大值,因为可能发现在start之前出现过的字符
            dict[s[i]]=i;//未重复,使数组中s[i]位的值赋为对应下标
            maxlen=max(maxlen,i-start);  
        }
        return maxlen;   
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325553496&siteId=291194637
Recommended