Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
本题是典型的动态规划问题。
主干思想:以abcabcbb为例,这个字符串的最大字串是 (不包含最后一个b的剩余字符串的abcabcb的最大字串) 和 (包含最后一个b的最大不重复字串)中较大值。
编写程序实现。
dynamic函数中的形参last表示字符串s的最大下标,及长度减去1的值。因为在c语言中仅仅通过s无法知道它的大小。
calcul_include_last函数用于计算包含最后一个字符的最长不重复子串。formor表示包含最后一个字符的最长不重复子串的左下标。
1 int calcul_include_last(char *s, int last) { 2 int formor = 0; 3 for(int i=last; i>formor; i--) { 4 for(int j=i-1; j>=formor; j--) 5 if(s[i]==s[j]) {formor = j+1; break;} 6 } 7 return last-formor+1; 8 } 9 10 int dynamic(char *s, int last) { 11 if (last==0) return 1; 12 13 int compare1 = dynamic(s, last-1); 14 int compare2 = calcul_include_last(s, last); 15 if(compare1 > compare2) 16 return compare1; 17 else 18 return compare2; 19 } 20 21 int lengthOfLongestSubstring(char* s) { 22 if(!strlen(s)) return 0; 23 24 return dynamic(s, strlen(s)-1); 25 }