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 的题。i代表substring的开始位置,j代表substring的结束位置。注意问题:
1第二个指针从前向后遍历还是从后向前遍历:从前向后,因为可能从第二个字符就开始重复,从后向前不能效率更高
2 第一个指针从哪个位置开始更新:从当前找到的重复字符的位置的下一个开始,形成一个新substring。
3 如何表示当前字符是否重复: 使用一个bool 数组,表示256个字符是否存在在当前substring
4 如何更新bool 数组,只更新头尾。因为两个重复字符之间的字符是不重复的。
5 最后需要比较maxLength和n-i,因为可能j一直到string末尾都没有遇见重复,但是没有更新maxLength
代码如下:
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.size();
        if (n == 0) return 0;
        if (n == 1) return 1;
        int i = 0;
        int j = 0;
        int maxLength = 0;
        bool characters[256] = { false };
        while (j < n) {
            if (characters[s[j]]) {
                maxLength = max(maxLength, j - i);
                while (s[i] != s[j]) {
                    characters[s[i]] = false;//recover the value for next substring
                    i++;
                }
                i++;//since substring between i and j are not repeated
                j++;
            }
            else {
                characters[s[j]] = true;
                j++;
            }
        }
        maxLength = max(maxLength, n - i);
        return maxLength;
    }
};







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值