Description

Notes

Testcase

Judge

Given a string, find the length of the longest substring without repeating characters.

Have you met this question in a real interview? Yes

Example

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.

Challenge

O(n) time

Tags

String Hash Table Two Pointers

Related Problems

Medium Longest Substring with At Most K Distinct Characters

class Solution {

public:

/\*\*

 \* @param s: a string

 \* @return: an integer 

 \*/

int lengthOfLongestSubstring\(string s\) {

    // write your code here

    unordered\_set<char> hash;

    int len = 0;

    int i = 0, j = 0;

    for \(; i < s.length\(\); ++i\) {

        while \(j < s.length\(\) && hash.find\(s\[j\]\) == hash.end\(\)\) {

            hash.insert\(s\[j\]\);

            ++j;

            if \(j - i > len\) {

                len = j - i;

            }

        }

        hash.erase\(s\[i\]\);

    }

    return len;

}

};

results matching ""

    No results matching ""