无重复字符的最长子串-leetcode刷题

  • Post author:
  • Post category:其他


问题描述

原题链接:



力扣


icon-default.png?t=M666
https://leetcode.cn/problems/longest-substring-without-repeating-characters/



解题思路

使用滑动窗口实现, 定义一个字符队列作为滑动窗口, 处理流程

循环遍历输入字符串:

滑动窗口是否已包含当前字符

包含–>把滑动窗口从开始直到重复字符全部pop掉

不包含 –> 当前字符压入滑动窗口

刷新最大长度结果

实现代码

class Solution {
public:
    int lengthOfLongestSubstring(string s) {

        deque<char> sliceWindow;
        int result = 0;
        for(int i = 0; i < s.length(); i++)
        {
            if(ContainChar(sliceWindow, s[i]))
            {
                LeftRemove(sliceWindow, s[i]);
            }
            sliceWindow.push_back(s[i]);

            if(sliceWindow.size() > result)
            {
                result = sliceWindow.size();
            }
        }

        return result;     
    }

    bool ContainChar(deque<char>& d, char target)
    {
        for(auto c : d)
        {
            if(c == target)
            {
                return true;
            }
        }

        return false;
    }

    void LeftRemove(deque<char>& d, char target)
    {
        while(true)
        {
            if(d.front() == target)
            {
                d.pop_front();
                break;
            }

            d.pop_front();
        }
    }
};



版权声明:本文为xiaoqiang321原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。