1. 程式人生 > >leetcode-3:Longest Substring Without Repeating Characters 最長無重複字元的子串

leetcode-3:Longest Substring Without Repeating Characters 最長無重複字元的子串

題目:

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.

給定一個字串,請你找出其中不含有重複字元的 最長子串 的長度。

示例 1:

輸入: "abcabcbb"
輸出: 3 
解釋: 因為無重複字元的最長子串是 "abc",所以其
長度為 3。

示例 2:

輸入: "bbbbb"
輸出: 1
解釋: 因為無重複字元的最長子串是 "b",所以其長度為 1。

示例 3:

輸入: "pwwkew"
輸出: 3
解釋: 因為無重複字元的最長子串是 "wke",所以其長度為 3。
     請注意,你的答案必須是 子串 的長度,"pwke" 是一個子序列,不是子串。

思路:給了我們一個字串,讓我們求最長的無重複字元的子串,注意這裡是子串,不是子序列,所以必須是連續的。建立一個256位大小的整型陣列來代替HashMap,這樣做的原因是ASCII表共能表示256個字元,所以可以記錄所有字元,然後我們需要定義兩個變數res和left,其中res用來記錄最長無重複子串的長度,left指向該無重複子串左邊的起始位置,然後我們遍歷整個字串,對於每一個遍歷到的字元,如果雜湊表中該字串對應的值為0,說明沒有遇到過該字元,則此時計算最長無重複子串,i - left +1,其中i是最長無重複子串最右邊的位置,left是最左邊的位置,還有一種情況也需要計算最長無重複子串,就是當雜湊表中的值小於left,這是由於此時出現過重複的字元,left的位置更新了,如果又遇到了新的字元,就要重新計算最長無重複子串。最後每次都要在雜湊表中將當前字元對應的值賦值為i+1。(利用滑動視窗思想)

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int m[256]={0},maxlen=0,left=0;
        for(int i=0;i<s.length();++i)
        {
            if(m[s[i]]==0 || m[s[i]]<left)   //從未出現過和未在當前滑動視窗內
                maxlen = max(maxlen,i-left+1);
            else 
            {
                left = m[s[i]];
            }
            m[s[i]] = i+1;
        }
        return maxlen;
    }
};