Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

What a juicy problem to solve :) My intuition is DP, but failed with TLE. Then I referred to:

http://leetcode.com/2011/05/longest-substring-without-repeating-characters.html

Essentially, it is Monotonous Queue I met last month !

So, another advice:

When you have a DP solution to a 1D space, think about the possibility of Monotonous Queue for a further optimization!

class Solution {
public:
    //     Idea is like Mono-Queue
    int lengthOfLongestSubstring(string s) {
        int len = s.length();
        if (len < 1) return len;

        int maxLen = 1;
        unordered_map<char, int> rec;
        int start = 0;
        int i;
        for (i = 0; i < len; i++)
        {
            char c = s[i];
            if (rec.find(c) == rec.end())
            {
                rec.insert(make_pair(c, i));
            }
            else
            {
                maxLen = std::max(maxLen, i - start);                
                
                int iFound = rec[c];
                for (int i = start; i <= iFound; i++)
                    rec.erase(s[i]);
                rec.insert(make_pair(c, i));
                start = iFound + 1;                
            }
        }
        maxLen = std::max(maxLen, i - start);
        return maxLen;
    }
};

 

posted on 2014-08-09 06:42  Tonix  阅读(135)  评论(0编辑  收藏  举报