[Leetcode] 3. Longest Substring without Repeating Characters 解题报告

题目:

 

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

Examples:

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.

 

思路:

 

典型的字符串问题中的“Two Pointers”的应用。可以借助一个hash表,维护一个不包含重复字符串的窗口,使用左右指针left,right滑动窗口大小。左右指针的滑动规则如下:

1)首先右指针right向右移动,直到遇到一个和窗口中有重复的字符。右指针在滑动过程中更新最大不重复子串的长度。

2)此时左指针向右移动到重复字符之后去,同时更新hash表中的字符。

该算法的时间复杂度为O(n),空间复杂度依然为O(n)。

在面试中需要注意英文中“subsequence”和“substring”的区别。前者中的邻接字符在原串中也必须是邻接的,而后者中的邻接字符在原串中未必需要邻接。

 

代码:

C++:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.size() == 0) 
            return 0;  
        int left = 0, right = 0, max_length = 0;  
        unordered_map<char, bool> hash;
        for(right = 0; right < s.size(); ++right)
        {
            while(hash.count(s[right]))
                hash.erase(s[left++]);
            hash[s[right]] = true;
            max_length = max(max_length, (int)hash.size());
        }
        return max_length;
    }
};

Python3:

class Solution:
    def lengthOfLongestSubstring(self, s: 'str') -> 'int':
        if len(s) == len(set(s)):   # this means every charchater is unique
            return len(s)
        d = {}                      # map from values to indices
        start = 0
        tmp = 0
        ans = 0
        for index, val in enumerate(s):
            if val in d and d[val]>= start:
                start = d[val] + 1
            d[val] = index
            tmp = index - start + 1
            ans = max(ans,tmp)
        return ans

 

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值