Longest Substring Without Repeating Characters (LeetCode)

Question:

https://leetcode.com/problems/longest-substring-without-repeating-characters/

 

从头往后读,如果碰到前面重复的字符,则新的子串从重复的字符后面开始算,所以需要一个hash table来记录前面出现的每个字符的位置(最后的)。

同时也需要有一个指针,记录当前子串的开始位置,如果重复的字符在这个指针之前的位置,就不用理会。

因为是string,字符的可能性最多是255,所以用一个255的数组来替代需要用到的hash table,能提高不少的性能。

 

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        
//        std::map<char, int> charFirstIndex;  // the position of char in current sub string
        
        int maxLength = 0;
        int startIndex = 0;
        
        int charFirstIndex[255];
        
        for (int i = 0; i < 255; i++)
            charFirstIndex[i] = -1;
        
        for (int i = 0; i < s.size(); i++)
        {
            if (charFirstIndex[s[i]] >= startIndex)
                startIndex = charFirstIndex[s[i]] + 1;
            
            //if (charFirstIndex.find(s[i]) != charFirstIndex.end() && charFirstIndex[s[i]] >= startIndex)
            //{
            //    startIndex = charFirstIndex[s[i]] + 1;
            //}
            
            charFirstIndex[s[i]] = i;
            
            if (i - startIndex + 1 > maxLength)
                maxLength = i-startIndex+1;
        }
        
        return maxLength;
    }
};

 

posted @ 2015-04-09 14:11  smileheart  阅读(130)  评论(0)    收藏  举报