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.
动态规划,注意空字符串。
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 int n = s.length(); 5 if (n == 0) { 6 return 0; 7 } 8 int *a = new int[n]; 9 int max = 1, tmp; 10 a[0] = 1; 11 bool flag; 12 for (int i = 1; i < n; ++i) { 13 flag = true; 14 tmp = 1; 15 for (int j = 1; j <= a[i-1]; ++j) { 16 if (s[i-j] == s[i]) { 17 tmp = j; 18 flag = false; 19 break; 20 } 21 } 22 a[i] = flag ? a[i-1] + 1 : tmp; 23 max = a[i] > max ? a[i] : max; 24 } 25 return max; 26 } 27 };
滑动窗口!
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 int len = 0; 5 bool flag[256] = {false}; 6 int start = 0; 7 for (int i = 0; i < s.length(); ++i) { 8 if (flag[s[i]]) { 9 while (s[start] != s[i]) { 10 flag[s[start]] = false; 11 ++start; 12 } 13 ++start; 14 } 15 flag[s[i]] = true; 16 len = max(len, i - start + 1); 17 } 18 return len; 19 } 20 };
还可以再优化一点!
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 int len = 0; 5 int pos[256]; 6 for (int i = 0; i < 256; ++i) pos[i] = -1; 7 int start = 0; 8 for (int i = 0; i < s.length(); ++i) { 9 if (pos[s[i]] >= start) { 10 start = pos[s[i]] + 1; 11 } 12 pos[s[i]] = i; 13 len = max(len, i - start + 1); 14 } 15 return len; 16 } 17 };