[LeetCode] 3. Longest Substring Without Repeating Characters

42 篇文章 0 订阅
37 篇文章 0 订阅

题目链接: https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

Description

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.

解题思路

题意为找到最长无重复字符的子串的长度。

因为共有 256 种不同的字符,所以可以用一个数组来记录每一个字符最后一次出现的下标。用变量 start 来记录当前子串第一个字符的下标,遍历字符串,若发现字符 s[i] 对应的最后一次出现的下标大于等于 start,即表示 s[i] 在该子串中已经出现过,则当前子串的下标区间为 [start, i - 1],更新长度记录。并且,新的子串起始位置应该为 s[i] 上次出现的下标后一个位置,这样才能保证最长这一个条件。

另外,由于更新长度记录是在遍历中进行的,因此若最长子串包含最后一个字符,在遍历过程中就不能更新该长度记录,所以要在遍历外边再加一个长度记录更新。

举个例子,s = "abac",记录字符最后一次出现下标的数组为 alpha[256]'a'ascii 码为 97。

  • i == 0, s[i] == 'a'start = 0, alpha[97] = 0,子串为 "a"
  • i == 1, s[i] == 'b'alpha[98] = 1,子串为 "ab"
  • i == 2, s[i] == 'a'alpha[97] == 0 >= start => 当前子串 "ab" 已经有 'a' 存在,更新长度记录为 2,并且应该从 'b' 开始下一个子串,所以 start = alpha[97] + 1,即为 1alpha[97] = 2,子串为 "ba"
  • i == 3, s[i] == 'c'alpha[99] = 3,子串为 "bac",更新长度记录为 3

Code

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> alpha(256, -1);
        int res = 0, start = 0;

        for (int i = 0; i < s.size(); ++i) {
            if (alpha[s[i]] >= start) {
                res = max(i - start, res);
                start = alpha[s[i]] + 1;
            }
            alpha[s[i]] = i;
        }
        res = max((int)(s.size() - start), res);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值