[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.
Solution:
class Solution { public: int lengthOfLongestSubstring(string s) { int length = s.length(); if(length < 2) return length; int *dp = new int[length]; int maxLen = 1; dp[0] = 1; for(int i = 1;i < length;i++) { int curLen = 0; bool noRepeat = true; for(int j = i - 1;j >= i - dp[i - 1];j--) { if(s[j] == s[i]) { curLen = i - j - 1; noRepeat = false; break; } } if(noRepeat) dp[i] = dp[i - 1] + 1; else dp[i] = curLen + 1; maxLen = max(maxLen, dp[i]); } //cout << maxLen << endl; return maxLen; } };