C++

Leetcode: 3. Longest Substring Without Repeating Characters


Description

Given a string, find the length of the longest substring without repeating characters.

Example

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.

思路

  • hash,将字符和出现位置进行hash
  • 对字符串从头到尾扫描一遍,维护一个不重复的子串。记录一个起始位置到当前位置为子串。
  • 扫描过程中,若出现相同字符,根据hash情况,判断此时的子串是否应该改变起始位置。

代码

  • 时间复杂度 O(n)
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int len = s.size();
        if(len == 0) return 0;
        
        vector<int> hash(256, -1);
        int max_len = 0, begin = 0;
        
        for(int i = 0; i < len; ++i){
            if(i == begin){
                hash[s[i]] = i;
                begin = i;
            }
            
            //判断该字符是否已经出现过,而且需要判断是否应该改变起始位置
            //若该字符的最近出现位置小于begin,即说明不在当前子串中,不需要改变
            else if(hash[s[i]] != -1 && hash[s[i]] >= begin){
                 begin = hash[s[i]] + 1;   
            }
            
            //修改s[i]最近出现位置
            hash[s[i]] = i;
           
            if(i - begin + 1 > max_len)
                max_len = i - begin + 1;
        }
        
        return max_len;
    }
};

作者:JeffLai,发布于:2018/08/29
原文:https://www.cnblogs.com/lengender-12/p/6756120.html