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 };
[Leetcode] Longest Substring Without Repeating Characters,布布扣,bubuko.com
[Leetcode] Longest Substring Without Repeating Characters
原文:http://www.cnblogs.com/easonliu/p/3634899.html