C++速通LeetCode中等第5题-无重复字符的最长字串

字串substr法,定义字串的头部和长度,和字串后一位对比,如果不存在重复元素则长度+1,存在重复元素则头部更新,长度重置。

cpp 复制代码
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        string s2;//存放s的前一部分,判断该部分有没有后一个字符
        int res = 1;
        int start = 0;//子序列第一个的序号
        int len = 1;//连续的前端子序列长度
        if(!s.size()) return 0;
        if(s[0] == ' ') return 1;
        for(start = 0; ; )
        {   
            if(start+len == s.size()) return res;
            s2 = s.substr(start,len);//一开始存放第一个字符
            if(count(s2.begin(),s2.end(),s[start+len]))//判断有没有重复,重复就重新开始计数
            {
                start += 1;//重复则start变到尾部后一位
                res = max(res,len);
                len = 1;
            }
            else//不重复start不变
            {
                len++;
                res = max(res,len);
            }
        }
        return res;
    }
};
相关推荐
峥嵘life5 小时前
Android16 311Y3 EAP-TLS 网络连接失败分析与修复总结
android·开发语言·人工智能·php
ShineWinsu5 小时前
对于C++:IO流状态的详细解析
c++·面试·io·cin·io流状态·goodbit·failbit
Lzg_na6 小时前
constexpr的优势
c++
mqiqe7 小时前
AgentScope Java Harness:4. 双层记忆系统 让 Agent 拥有真正的“长期大脑“
java·开发语言
想吃火锅10057 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
gugucoding7 小时前
46. 【Java】JUC并发工具:让并发更简单
java·开发语言
王维同学8 小时前
进程模块枚举、映像身份与线程启动地址关联
c++·windows·安全
hold?fish:palm8 小时前
24 回文链表
数据结构·c++·链表
举手8 小时前
Dispatcher模块剖析
linux·c++
Nil2088 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵