导航

LeetCode 3. Longest Substring Without Repeating Characters

Posted on 2017-01-09 00:03  CSU蛋李  阅读(111)  评论(0编辑  收藏  举报

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.

 

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if ("" == s)return 0;
        map<char, size_t> char2uintMap;
        char ch = s[0];
        size_t ret_length = 0;
        size_t temp_length = 0;

        for (size_t i = 0;i < s.length();++i)
        {
            if (char2uintMap.find(s[i]) == char2uintMap.end())
            {
                ++temp_length;
                char2uintMap[s[i]] = 1;
            }else
            {
                if (ret_length < temp_length)
                {
                    ret_length = temp_length;
                }
                
                for (int j = i - temp_length;j < i;++j)
                {
                    if (s[j] == s[i])
                    {
                        break;
                    }
                    else
                    {
                        char2uintMap.erase(s[j]);
                        --temp_length;
                    }
                }
            }
        }
        

        return ret_length<temp_length?temp_length:ret_length;
    }
};