[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.

这个题目想了挺久的,最后参考了别人的解法。用两个指针,一个指向当前子串的头,一个指向尾,尾指针不断往后扫描,当有字符前面出现过了,记录当前子串长度和最优解的比较结果。然后头指针不断往后扫描,直到扫描到一个字符和尾指针相同,则尾指针继续扫描,当尾指针到达字符串结尾,算法结束。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        bool exist[256] = {false};
        int maxLen = 0;
        int i = 0, j = 0;
        int n = s.size();
        while (j < n)
        {
            if (exist[s[j]])
            {
                maxLen = max(maxLen, j - i);
                for (;s[i] != s[j]; i++)
                    exist[s[i]] = false;
                i++;
                j++;
            }
            else
            {
                exist[s[j]] = true;
                j++;
            }
        }
        maxLen = max(maxLen, n - i);
        return maxLen;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值