3. Longest Substring Without Repeating Characters(無重複字符的最長子串)

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.

2 C++

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int begin = 0;
        int result = 0;
        string word = "";
        int word_map[128] = {0};
        for(int i=0; i<s.length(); i++) {
            word_map[s[i]]++;
            if(word_map[s[i]] == 1) {
                word += s[i];
                if(result < word.length())
                    result = word.length();
            }
            else {
                while(begin < i && word_map[s[i]] > 1) {
                    word_map[s[begin]]--;
                    begin++;
                }
                word = "";
                for(int j=begin; j<=i; j++) {
                    word += s[j];
                }
            }
        }
        return result;

    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章