A general solution allowing at most k times repeating for each characters


  • 0
    G

    The thought is simple, use a hash map to record how many times the character appears, and check if they appear more than once. Use two pointers to scan the substring. The method could be modified to at most k times repeating for every character.

    int lengthOfLongestSubstring(string s) {
            int sheet[256] = {0};
            int n = s.size();
            int ret = 0;
            int i = 0, j = 0;
            while (j < n) {
                sheet[s[j] - ' '] += 1;
                if (sheet[s[j] - ' '] > 1) {
                    while (sheet[s[j] - ' '] > 1) {
                        sheet[s[i] - ' '] -= 1;
                        i++;
                    }
                    j++;
                }
                else {
                    ret = max(ret, j - i + 1);
                    j++;
                }
            }
            return ret;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.