zoukankan      html  css  js  c++  java
  • [LeetCode] Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.

    解题思路

    设置左右两个指针。左右指针之间的字符没有出现反复,则右指针向右移动。否则左指针向右移动(直到没有反复字符为止)。而且统计最大字符数。

    实现代码

    // Rumtime: 60 ms
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            set<int> res;
            int maxLen = 0;
            int left = 0;
            int i;
            for (i = 0; i < s.size(); i++)
            {
                if (res.find(s[i]) != res.end())
                {
                    maxLen = max(maxLen, i - left);
                    while (s[left] != s[i])
                    {
                        res.erase(s[left++]);
                    }
                    left++;
                }
                else
                {
                    res.insert(s[i]);
                }
            }
    
            maxLen = max(maxLen, i - left);
    
            return maxLen;
        }
    };
  • 相关阅读:
    hdu4059 The Boss on Mars
    cf475D CGCDSSQ
    HDU
    cf1447D Catching Cheaters
    cf1440 Greedy Shopping
    Treats for the Cows
    dp废物学会了记录路径
    D. Jzzhu and Cities
    cf1359D Yet Another Yet Another Task
    关于sg函数打表的理解
  • 原文地址:https://www.cnblogs.com/blfbuaa/p/7222319.html
Copyright © 2011-2022 走看看