Longest Substring Without Repeating Characters -LeetCode OJ

Longest Substring Without Repeating Characters ---LeetCode OJ

题目描述:

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.

思路:用hashtable来标记每个字符出现的位置

代码:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(s.size() == 0) return 0;
        int cnt=0;
        int hash[256];
        int maxlen=-1;
        memset(hash,-1,sizeof(hash));
        
        for(int i=0; i<s.size(); i++)
        {
            char ch = s[i];
            if(hash[ch] == -1)
            {
                cnt++;
                hash[ch] = i;
                maxlen = max(maxlen,cnt);
            }
            else 
            {
               int index = hash[ch];
               //cnt = i-index;
               for(int j=i-cnt; j<=index; j++)
               {
                   hash[s[j]] = -1;
               }
               cnt = i-index;
               hash[ch]=i;
               maxlen = max(maxlen,cnt);
            }
        }
        return maxlen;
    }
};