Given a string, find the length of the longest substring without repeating characters.
Example 1:
1 2 3
Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.
Example 2:
1 2 3
Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
Example 3:
1 2 3 4
Input: "pwwkew" Output: 3 Explanation: 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.
intlengthOfLongestSubstring(char* s) { int longest = 1, sublong = 1; int i = 0, j = 0; if (!s[0]) return0; while(s[++j]) { for (int k = i; k < j; k++) { if (s[j] == s[k]) { longest = longest > sublong ? longest : sublong; i = k + 1; sublong = j - i; break; } } sublong++; } longest = longest > sublong ? longest : sublong; return longest; }
结果
1 2
Runtime: 12 ms, faster than 89.94% of C online submissions for Longest Substring Without Repeating Characters. Memory Usage: 12.5 MB, less than 83.11% of C online submissions for Longest Substring Without Repeating Characters.
intlengthOfLongestSubstring(char* s) { int x[256] = { -1 }; // can not set to -1 on some compiler for (int i=0; i<256; i++) x[i] = -1; int longest = 0, pos = -1, i = -1; while(s[++i]) { pos = x[s[i]] > pos ? x[s[i]] : pos; x[s[i]] = i; longest = longest < (i-pos) ? i-pos : longest; } return longest; }
结果
1 2
Runtime: 12 ms, faster than 89.94% of C online submissions for Longest Substring Without Repeating Characters. Memory Usage: 12.4 MB, less than 96.62% of C online submissions for Longest Substring Without Repeating Characters.