LeetCode 3. Longest Substring Without Repeating Characters

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.

三、解题思路

Set

  • 判断是否出现重复,可以考虑使用set 集合来做。因为集合中的值是不允许重复的。首先遍历一遍string 添加到一个set中,set的大小,即时不重复子串的最大长度。
  • 然后依次判断以 i 开头的不重复子串的长度是多少,并不断更新最大值,如果最大值达到了上面求出的最大子串的长度,那么就直接返回。在计算以 i 开头的子串长度时,遇到重复的直接返回,否则长度加一并继续遍历。
  • 这个算法不是那么棒呦,复杂度应该是O(n2)
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.size() == 0)return 0;
        if(s.size() == 1)return 1;
        int max = 0;
        set<char> tot;
        for (int i = 0, n = s.size(); i < n; ++i) {
            tot.insert(s[i]);
        }
        for (int i = 0, n = s.size(); i < n; ++i) {
            set<char> cache;
            cache.insert(s[i]);
            int count = 1;
            for (int j = i+1; j < n; ++j) {
                if(cache.find(s[j]) == cache.end()){
                    cache.insert(s[j]);
                    count++;
                }else{
                    break;
                }
            }
            if(count > max)max = count;
            if(max == tot.size())break;
        }
        return max;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值