博客
关于我
无重复字符的最长子串(滑动窗口+双指针)
阅读量:290 次
发布时间:2019-03-01

本文共 973 字,大约阅读时间需要 3 分钟。

滑动窗口法+双指针解决最长子字符串问题

在处理字符串问题时,滑动窗口法常常被用来解决最长子字符串问题,该问题要求找出字符串中最长的子串,其中所有字符均不重复。这种方法通过双指针技术,有效地维护了窗口内的唯一字符,从而在O(n)时间复杂度内完成任务。

核心思路是通过左右两个指针来维护当前窗口内的唯一字符。当遇到重复字符时,左指针会向右移动,使得窗口内的字符保持唯一。这种方法的时间复杂度为O(n),因为每个字符最多被访问一次。

代码实现如下:

int lengthOfLongestSubstring(string s) {    if (s.size() == 0)        return 0;    int left = 0, right = 0;    int maxlength = 1;    while (right <= s.size() - 1) {        for (int temp_left = left; temp_left < right; ++temp_left) {            if (s[right] == s[temp_left]) {                left = temp_left + 1;                break;            }        }        if (right - left + 1 > maxlength) {            maxlength = right - left + 1;        }        right++;    }    return maxlength;}

代码解释:

  • 初始化左指针left和右指针right都为0,标记当前窗口的左右边界。
  • 初始化最长子串的长度为1,假设最坏情况下只有一个字符。
  • 遍历字符串,右指针逐一向右移动。
  • 对于当前右指针位置的字符,检查从左指针开始到当前右指针位置之间的所有字符。
  • 如果发现重复字符,则将左指针移动到重复字符后一个位置,确保窗口内的字符唯一。
  • 更新最大长度,如果当前窗口长度大于之前记录的最大长度。
  • 右指针继续向右移动,重复上述步骤。
  • 最终返回最长子串的长度。
  • 这种方法通过动态调整窗口边界,确保窗口内字符唯一,能够高效地解决问题。

    转载地址:http://tvmt.baihongyu.com/

    你可能感兴趣的文章
    Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.7 Parameters vs Hyperparameters
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>