码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Longest Substring Without Repeating Characters

时间:2017-07-22 21:11:05      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:cab   amp   turn   add   cpp   down   字符   ras   line   

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;
    }
};

[LeetCode] Longest Substring Without Repeating Characters

标签:cab   amp   turn   add   cpp   down   字符   ras   line   

原文地址:http://www.cnblogs.com/blfbuaa/p/7222319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!