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