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.
算法思想:
首先想到可以用动态规划,设dp[i]表示的是与i位置元素相同的上一个元素位置
class Solution { public: int lengthOfLongestSubstring(string s) { const int len = s.length(); int *dp = new int[len+2]; int last[256]; for (int i = 0; i < 256; ++i) last[i] = len; dp[len] = len; for (int i = len - 1; i >= 0; --i) { dp[i] = min(dp[i+1], last[s[i]] - 1); last[s[i]] = i; } int ans = -1; for (int i = 0; i < len; ++i) { const int ret = dp[i] - i; ans = max(ans,ret); } return ans + 1; } };
有个更加精炼的版本
class Solution { public: int lengthOfLongestSubstring(string s) { int last[256];//保存字符上一次出现的位置 memset(last, -1, sizeof(last)); int idx = -1, ans = 0;//idx为当前子串的开始位置-1 for (int i = 0; i < s.size(); i++) { if (last[s[i]] > idx)//如果当前字符出现过,那么当前子串的起始位置为这个字符上一次出现的位置+1 { idx = last[s[i]]; } ans = max(ans,i-idx); last[s[i]] = i; } return ans; } };