LeetCode #3 : Longest Substring

2017-02-25  本文已影响11人  雒霭

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.


记录每个字母上一次出现的位置,将位置存储在map中,每次遇到下一个字母便在map中查找这个字母上次遇到的位置,获取这段距离,用num记录最大值并返回。

int lengthOfLongestSubstring(string s) {
    if (s.length() == 0) return 0;
    map<char, int> mp;
    int num = 0;
    for (int i = 0, j = 0; i < s.length(); i++) {
        map<char, int>::iterator it = mp.find(s[i]);
        if (it != mp.end()) {
            j = max(j, mp[s[i]] + 1);
        }
        mp[s[i]] = i;
        num = max(num, i - j + 1);
    }
    return num;
}
上一篇 下一篇

猜你喜欢

热点阅读