3. 无重复字符的最长字符串

本文介绍了使用双指针法解决LeetCode第3题——无重复字符的最长子串。通过左右指针移动和字符串截取操作,找出不包含重复字符的连续子串,并更新最长子串长度。关键点在于`s1.find(s2)`和`s.substr()`的运用。
摘要由CSDN通过智能技术生成

 双指针解法,用左边的substr去找右边的substr,如果没找到,右指针往右移,cnt++,更新ans,更新左边的substr;如果找到了,左指针往右移,更新ans,cnt--,更新左边的substr。直到右指针越界。

cpp的2个技术点:

s1.find(s2),返回第一个找到s2的位置,否则返回-1。
s.substr(index,len),截取s串中从index位置起的len个数。

/*
 * @lc app=leetcode.cn id=3 lang=cpp
 *
 * [3] 无重复字符的最长子串
 */

// @lc code=start
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int slen = s.length();
        int ans = 0;
        if (slen == 0) return ans;
        int lp = 0, rp = 0;
        ans += 1; // 从index=0开始     
        string st = s.substr(lp, 1);
        cout << st;
        int cnt = 1;
        rp += 1; // rp指向1
        while (rp<slen)
        {                                  
            int pos = st.find(s.substr(rp, 1));
            if (pos != -1) {
                // 找到一个,左指针右移,更新st
                lp += 1;
                st = s.substr(lp, cnt-1);
                if (cnt > ans) ans = cnt;
                cnt -= 1; // cnt初始化
            }
            else {
                // 没有找到,rp右移
                cnt += 1;
                rp += 1;
                st = s.substr(lp, cnt);
                if (cnt > ans) ans = cnt;
            }

        }
        return ans;
    }
};
// @lc code=end

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值