3. Longest Substring Without Repeating Characters简单高效解法

// Author : yqtao
// Date : 2016-7-3
// Email : [email protected]
/********************************************************************************************************
*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.
*********************************************************************************************************/
方法1.用map

int lengthOfLongestSubstring(string s) 
{
    map<char, int> m;   
    int maxLen = 0;
    int lastRepeatPos = -1;   //last repeatpos ,so i- lastrepeatpos is the length;
    for (int i = 0; i<s.size(); i++) {
        if (m.find(s[i]) != m.end() && lastRepeatPos < m[s[i]]) {
            lastRepeatPos = m[s[i]];
        }
        if (i - lastRepeatPos > maxLen) {
            maxLen = i - lastRepeatPos;
        }
        m[s[i]] = i;
    }
    return maxLen;
}

方法2,不用map,但是思想相同

//without using map,but,the idea is the same with map
int lengthOfLongestSubstring1(string s) {
    vector<int> dict(256, -1);
    int maxLen = 0, lastRepeatPos = -1;
    for (int i = 0; i != s.length(); i++) {
        if (dict[s[i]]!=-1&&dict[s[i]] > lastRepeatPos)
            lastRepeatPos = dict[s[i]];
        dict[s[i]] = i;
        if (i - lastRepeatPos > maxLen) {
            maxLen = i - lastRepeatPos;
        }
    }
    return maxLen;
}

你可能感兴趣的:(LeetCode)