首页 > 代码库 > [leetcode]

[leetcode]

问题描述:

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.


算法思路:

设置一个map<char,int>用来记录字符和字符位置的pos,当出现重复字符时,说明前面的字符串和当前字符串不能构成一个符合条件解字符串,则找到与当前字符相同的字符在前面出现的位置,删除该字符串之前的所有字符。在该过程中维持一个max变量 用来记录最大字符串的长度。


代码:

int lengthOfLongestSubstring(string s) {
        if(s.size() == 0)
            return 0;
        
        int max = 0;
        map<char,int> charMap;
        map<char,int>::iterator iter;

        for(int i = 0; i < s.size(); i++)
        {
            char ch = s[i];
            iter = charMap.find(ch);
            if(iter == charMap.end())
            {
                charMap.insert(make_pair(ch,i));
                if(charMap.size() > max)
                    max = charMap.size();
            }
            else
            {
                int pos = iter->second;
                vector<pair<char,int> > vec(charMap.begin(),charMap.end());
                for(int j = 0; j < vec.size(); j++)
                    if(vec[j].second < pos)
                        charMap.erase(vec[j].first);
                charMap[ch] = i;
            }
        }
        max = (charMap.size() > max)? charMap.size():max;
        return max;
        
    }


[leetcode]