【Longest Substring Without Repeating Characters】cpp

题目:

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.

代码:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
            map<char, int> visited;
            for ( char c='a'; c<='z'; ++c ) visited[c]=-1;
            int begin = 0;
            int longest_substring = 0;
            for ( int i = 0; i < s.size(); ++i )
            {
                char curr = s[i];
                if ( visited[curr]>=begin )
                {
                    longest_substring = std::max(longest_substring, i-begin);
                    begin = visited[curr]+1;
                }
                visited[curr]=i;
            }
            return std::max((int)s.size()-begin, longest_substring);
    }
};

tips:

Greedy解法,主要维护以下两个内容。

维护一个哈希表:<字母,上一次字母出现的位置>

维护一个begin:表示不重复字符串的起始位置

如果当前字母在之前出现过,且出现的位置大于等于begin,则证明遇到了重复的字符;更新begin的位置为该字母上一次出现的位置+1。

在整个过程中,每次遇到不重复的字符时,就往后走。

这里要注意边界条件,即最长的字符串包含最后s的最后一个字符。

则在推出循环后,要再更新一次longest_substring。

===============================================

第二次过这道题,还是用hashmap的思路,第一次超时了,原因是想删除在local长度之前的那些hashmap表中的字符。

第二次修改了一下,hashmap表中的字符即使有重复的也不要紧,只要不在local长度范围内,都可以接受继续往后走,然后更新字符最新的位置就可以了。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
            map<char, int> charPosition;
            int global = 0;
            int local = 0;
            for ( int i=0; i<s.size(); ++i )
            {
                if ( charPosition.find(s[i])==charPosition.end() || charPosition[s[i]]<i-local )
                {
                    charPosition[s[i]] = i;
                    local++;
                }
                else
                {
                    global = max(global, local);
                    local = i - charPosition[s[i]];
                    charPosition[s[i]] = i;
                }
            }
            return max(global, local);
    }
};
原文地址:https://www.cnblogs.com/xbf9xbf/p/4540396.html