Leetcode Longest Substring Without Repeating Characters

OpenSoucre發表於2014-07-04

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) {
        unordered_map<char,int> hash_map;
        int maxLen = 0,start = 0;
        for(int i = 0; i < s.length(); ++ i){
            if(hash_map.find(s[i])!=hash_map.end() && hash_map[s[i]] >=start){
                start = hash_map[s[i]]+1;
            }
            hash_map[s[i]] = i;
            maxLen = max(maxLen,i-start+1);
        }
        return maxLen;
    }
};

 

相關文章