LeetCode03. 无重复字符的最长子串 [中等]

题目描述:3. 无重复字符的最长子串

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

示例1:

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

示例2:

输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1

示例3:

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

我的解题:

分别用head和tail指示正在读取的子字符串的首尾

num表示已求得的子串的最长长度

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_map<char,int> m;
        int num=0;
        int head=0,tail=0;
        while(head<s.length()&&tail<s.length()){
            if(m.find(s[tail])==m.end()){
                m[s[tail]]=tail;
                tail++;
                num=max(num,tail-head);
            }
            else{
                m.erase(s[head]);
                head++;
            }
        }
        return num;
    }
};

执行结果:

但是我的用时和内存消耗好像不太好

发布了15 篇原创文章 · 获赞 0 · 访问量 101

猜你喜欢

转载自blog.csdn.net/qq_41041762/article/details/105078761