LeetCode——3. Longest Substring Without Repeating Characters
1.題目詳情
Given a string, find the length of the longest substring without repeating characters. 給出一個字串,找到最長的且沒有重複字元的子串。
Example 1:
Input: “abcabcbb” Output: 3 Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: “bbbbb” Output: 1 Explanation: The answer is “b”, with the length of 1.
Example 3:
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.
完善下面程式碼:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
}
};
2.解題方法
2.1 解法1
解法一類似於暴力破解:執行for迴圈,從每個字元開始,不斷向後延伸,將擴充套件到的字元放入到一個數組中,遇到重複字元再停止,然後比較現有子串長度與記錄下來的最大長度,選出最大長度。 優化
class Solution { public: int lengthOfLongestSubstring(string s) { int start = 0, maxLength = 0, size = s.size(); while (start < size - maxLength) { int chars[256] = {0}; int index = start; int length = 0; int now = (int)s[index]; while (chars[now] == 0 && index < size) { index++; chars[now] = 1; length++; now = (int)s[index]; } if (length > maxLength) maxLength = length; start++; } return maxLength; } };
這裡的時間花費為20ms。
2.2 解法2
解法二是對解法一的優化,因為從一個字元開始擴充套件延伸字串,直到遇到一個重複在延伸的字串中已有的字元,那麼可以確定在開始字元到已有字元間的每個字元開始延伸的字串都比不上現有的字串,所以可以直接從已有字元的下一個字元重新開始延伸字串。 如果將開始延伸字串的字元認為是start,則start將不斷的與重複字元替換,這也是延伸出來的子串的最左邊。子串的右邊則是不斷的加1,向後延伸。 所以這裡需要用兩個陣列,記錄每個字元的位置與現有的重複字元。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int size = s.size();
int chars[256] = {0};
int locas[256] = {0};
int start = 0;
int maxLength = 0;
for (int i = 0; i < size; i++) {
int now = s[i];
start = max(start, (chars[now] ? (locas[now] + 1) : 0));
maxLength = max(maxLength, i - start + 1);
chars[now] = 1;
locas[now] = i;
}
return maxLength;
}
};