Longest Substring Without Repeating Characters
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.
记一个满有趣的解法
首先是我的暴力解法= =
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 if(s.empty()) 5 return 0; 6 int length = 1; 7 int len = 1; 8 for(int i = 1; i < s.size(); i++) 9 { 10 if(s[i] != s[i-1]) 11 { 12 int j = i - 2; 13 int n = len - 1; 14 while(n) 15 { 16 if(s[j] == s[i]) 17 { 18 len = i - j; 19 break; 20 } else 21 { 22 n--; 23 j--; 24 } 25 } 26 if(j == i - len - 1) 27 { 28 len++; 29 length = max(length, len); 30 } 31 } else 32 len = 1; 33 } 34 return length; 35 } 36 };
别人的时间复杂度为O(n)的解法...
思想是利用dict[]记录出现过的字符在s中的下标。如果 if(dict[s[i]] > start) 为真,则说明字符再次出现,此时用start记录前一次出现时的下标,然后更新dict[]中该字符的值。可以看到越先出现字符lict[]的值越小,因为i是递增的,这保证了当有重复的字符出现时,
dict[s[i]] 必然大于 start,所以start记录的肯定是最后出现的重复字符的前一次出现时的下标。还是看代码吧,说着太绕了。
1 int lengthOfLongestSubstring(string s) { 2 vector<int> dict(256, -1); 3 int maxLen = 0, start = -1; 4 for (int i = 0; i != s.length(); i++) { 5 if (dict[s[i]] > start) 6 start = dict[s[i]]; 7 dict[s[i]] = i; 8 maxLen = max(maxLen, i - start); 9 } 10 return maxLen; 11 }
最近在leetcode刷题,遇到有意思的才会更新到博客,所以最近都没怎么更新= =