Difficulty: Medium算法
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.翻譯
class Solution { public: int lengthOfLongestSubstring(string s) { } };
難度係數:中等code
給定一個字符串,找其無重複字符的最長子串的長度。索引
例如: "abcabcbb"的無重複字符的最長子串是"abc",長度爲3。 "bbbbb"的無重複字符的最長子串是"b",長度爲1leetcode
遍歷字符串,若是前面有重複的,就把前面離如今這個字符最近的重複的字符的索引記錄在repeatIndex, 若是沒有重複,則也爲repeatIndex。
注意: 當前的repeatIndex要大於之前記錄的repeatIndex,小於則不更新repeatIndex下面第三種狀況字符串
如:
"abcabcbb" -> $\frac{abcabcbb}{00012357}$ -> $\frac{12345678}{00012357}$ -> 3get
"bbabcdb" -> $\frac{bbabcdb}{0112224}$ -> $\frac{1234567}{0112224}$ -> 4string
"abba" -> $\frac{abba}{0022}$ -> $\frac{1234}{0022}$ -> 2hash
找重複的時候能夠用hashmap的方法來下降時間複雜度, string的字符爲key, 索引爲value。it
class Solution { public: int lengthOfLongestSubstring(string s) { int maxLen = 0; int repeatIndex = 0; int size = static_cast<int>(s.size()); for (int i = 0; i < size; ++i){ for (int j = i - 1; j >= 0; --j) { if (s[i] == s[j]){ if (j > repeatIndex){ repeatIndex = j; } break; } } if (maxLen < i -repeatIndex){ maxLen = i - repeatIndex; } } return maxLen; } }
class Solution { public: int lengthOfLongestSubstring(string s) { int maxLen = 0; int repeatIndex = 0; int size = static_cast<int>(s.size()); map<char, int> tempHash; for (int i = 0; i < size; ++i){ if (tempHash.find(s[i]) != tempHash.end() && tempHash[s[i]] > repeatIndex){ repeatIndex = tempHash[s[i]]; } if (maxLen < i -repeatIndex){ maxLen = i - repeatIndex; } tempHash[s[i]] = i; } return maxLen; } }