3. Longest Substring Without Repeating Characters

https://leetcode.com/problems/longest-substring-without-repeating-characters/

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

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

算法思路:

配合map的双指针技术

class Solution {//slide window O(n) O(1) 8ms
public:
    int lengthOfLongestSubstring(string s) {
        int n=s.size();
        if(n==0 || n==1) return n;
        
        int freq[256]={0}; //set的作用
        int l=0,r=0;       //[l...r]没有重复子串
        int res=0;
        while(l<n && r<n){
            if(freq[s[r]]==0){
                freq[s[r++]]++;
                res=max(res,r-l);
            }else freq[s[l++]]--;
        }
        
        return res;
    }
};

The above solution requires at most 2n steps. In fact, it could be optimized to require only n steps. Instead of using a set to tell if a character exists or not, we could define a mapping of the characters to its index. Then we can skip the characters immediately when we found a repeated character.

The reason is that if s[r] have a duplicate in the range [l, r) with index r', we don't need to increase l little by little. We can skip all the elements in the range [l, r'] and let l to be r' + 1 directly.

class Solution {//slide window O(n) O(1) 8ms,前一个算法真实时间复杂度是O(2n)
public:
    int lengthOfLongestSubstring(string s) {
        int n=s.size();
        if(n==0 || n==1) return n;
        
        int index[256]={0}; //改变使之成为map的作用,记录该元素的位置,即角标值+1,区分0,0表示没有
        int l=0,r=0;        //[l...r]没有重复子串
        int res=0;
        while(r<n){
            l=max(index[s[r]],l);
            res=max(res,r-l+1);
            index[s[r]]=r+1;
            r++;
        }
        
        return res;
    }
};

扩展:

Java (Assuming ASCII 128)

The previous implements all have no assumption on the charset of the string s.

If we know that the charset is rather small, we can replace the Map with an integer array as direct access table.

Commonly used tables are:

  • int[26] for Letters 'a' - 'z' or 'A' - 'Z'
  • int[128] for ASCII
  • int[256] for Extended ASCII

参考资料:

https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值