LeetCode题目详解(二)——无重复字符的最长子串

题目描述

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:

输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:

输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-ch

思路解析

即目前出现的连续字符中不能存在重复字符,那就利用某种数据结构将从未出现的字符储存下,并记录当前串的长度,出现重复则删除这个字符,这个字符后的子串成为一个新串,继续上述操作,最终取记录的最大长度就是题目的解。问题就在于怎么判断重复,如果是数组或链表的话需要每次都从头到尾扫描,时间复杂度很高。因此需要一种方法可以快速检索,C++STL中的set可以解决快速检索的问题。

完整code:

#include <bits/stdc++.h>

using namespace std;
class Solution
{
public:
    int lengthOfLongestSubstring(string s)
    {
        set<char> container;
        int left = 0;
        int result = 0;
        int index = 0;
        while(index < s.size()){
            if(container.find(s[index]) == container.end())
            {
                container.insert(s[index++]);
                result = max(result,(int)container.size());
            }
            else{
                container.erase(s[left++]);
            }
        }
        return result;
    }
};

int main()
{
    string s;
    cin>>s;
    Solution Sve;
    cout<<Sve.lengthOfLongestSubstring(s);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章