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

问题描述

原题链接:力扣icon-default.png?t=M666https://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();
        }
    }
};

posted @ 2022-08-07 19:03  飞天赤狐  阅读(15)  评论(0)    收藏  举报