[3, Medium, C++] Longest Substring Without Repeating Characters

Problem:

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.

Analysis:

To solve this question, the program first caches a set of distinct characters of the string and runs from the first one to the last one to check whether a repeated character of the set is met. If such character is met, remove all ones before the repeated character. The key point of this method is to locate the repeated one in the quickest way.The method here is a typical one. We use a characteristic array whose index is the ascii value of a character and value is the index this character. For each character of the string, if the corresponding characteristic value of this character is greater or equal of the current sub-string, it means that a repeated character is found. Then, update the local_max_length of the sub-string and new start-checking-point. 

Sample Code:

    int lengthOfLongestSubstring(string s) {
        if(s.size() <= 1)
            return s.size();
            
        int max_length = 0;
        vector<int> char_seq_index(256, -1);
        int start_point = 0;
        int local_max_length = 0;
        for(int i = 0; i < s.size(); ++i) {
            if(char_seq_index[s[i]] >= start_point) {
                local_max_length -= char_seq_index[s[i]] + 1 - start_point;
                start_point = char_seq_index[s[i]] + 1;
            }
            
            char_seq_index[s[i]] = i;
            ++local_max_length;
            
            if(local_max_length > max_length)
                max_length = local_max_length;
        }
        
        return max_length;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值