3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

题目要求找出不包含重复字母的最长子序列长度。

  • 错误的思路:使用unordered_set容器,遍历整个字符串,遇到无法插入容器的情况,说明有重复字母,此时统计容器中元素的个数,然后清空整个容器,重新开始插入字符。遍历结束后,即可求出最大的字符串长度。
  1. 第一次错误:没有考虑只有1个元素时的情况
  2. 第二次错误:代码逻辑错误,对于类似于"abcab"的字符串统计错误
  • 改进后的思路:unordered_set<char>容器,记录两个指针left, right,遍历字符串。如果容器中已包含字符s[right],则在set中一直删除元素直到重复的字符也被删除,删的过程中更新left的值。统计长度len == right - left + 1 == set.size()
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int n = s.size();
            if (n == 0)
                return 0;
                
            int maxlen = 0;
            int left = 0, right = 0;
            unordered_set<char> con;
            while (right <= n - 1) {
                if (con.find(s[right]) == con.end()) {
                    con.insert(s[right]);
                    ++right;
                    
                    int curlen = con.size();
                    maxlen = max(maxlen, curlen);
                } else {
                    con.erase(s[left]);
                    ++left;
                }
            }
            return maxlen;
        }
    };

     

posted @ 2017-06-16 10:25  NaiveCoder  阅读(110)  评论(0)    收藏  举报