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;
    }
};
相关推荐
爱写Bug的浮游1 小时前
unique_ptr 零开销的真相与边界
c++·facebook
Pniubi1 小时前
Java为什么要分堆和栈
java·开发语言
xiaoye-duck1 小时前
《C++ 项目:手写大模型接入 SDK》ChatGPT接口设计(下):流式响应实现和测试
网络·c++·语言模型·chatgpt
小小晓.2 小时前
Qt 对话框、QLineEdit 与布局管理实战详解
开发语言·qt
炸薯条!2 小时前
博客系统测试报告
开发语言·lua
Evand J3 小时前
【MATLAB例程12】永磁同步电机基于增广无迹卡尔曼滤波的未知负载转矩在线观测
开发语言·matlab
一去不复返的通信er3 小时前
排序 + 双指针:力扣15三数之和
算法·leetcode
文丑颜不良啊3 小时前
LeetCode1901~1920题目解析
java·leetcode
落樱弥城3 小时前
Perf 逐步探查性能缺口并优化
c++·性能优化
Pniubi3 小时前
力扣3无重复字符的最长字串(滑动窗口)
算法·leetcode·职场和发展