【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 asubstring, "pwke" is a subsequence and not a substring.


给定一个字符串,求不包含重复字符的最长子串(连续的字符)的长度。


解题思路:

要使得子串中不包含重复的字符,可以考虑将字符串从头扫到尾,用一个布尔数组记录当前子串使用的字符,这样可以避免每次生成一个子串后重新判断是否有重复字符。

使用布尔数组的时间复杂度为O(1);若使用STL的set,时间复杂度为O(log(n)).

使用一个队列记录子串的字符,每次读取字符串中的一个字符时,判断之前构成的子串是否包含这个字符。若包含,则将队列中的首字符弹出,相当于删掉当前的子串的前缀。最后将新字符加入子串中。



参考代码:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        bool vis[512];
        memset(vis,0,sizeof(vis));
        queue<char> q;
        int maxLen = 0;
        for (char c:s){
            while(vis[c]){
                char x = q.front();
                q.pop();
                vis[x] = false;
            }
            vis[c] = true;
            q.push(c);
            if (q.size() > maxLen)maxLen = q.size();
        }
        return maxLen;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值