"Longest Substring Without Repeating Characters"

Given a string, the goal is to find the length of the longest substring without repeating characters. For example, given the string "abcabcbb", the longest substring would be " abc", with a length of 3.

Problem

Given a string, find the length of the longest substring without repeating characters.
Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3.

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <string>
#include <unordered_map>

using namespace std;

int lengthOfLongestSubstring(string s) {
    unordered_map<char, int> map;
    int maxLen = 0;
    int curLen = 0;
    int start = 0;
    for (int i = 0; i < s.length(); i++) {
        if (map.find(s[i]) == map.end()) {
            map[s[i]] = i;
            curLen++;
        } else {
            if (map[s[i]] >= start) {
                start = map[s[i]] + 1;
                curLen = i - map[s[i]];
            } else {
                curLen++;
            }
            map[s[i]] = i;
        }
        maxLen = max(maxLen, curLen);
    }
    return maxLen;
}

int main() {
    string s = "abcabcbb";
    cout << lengthOfLongestSubstring (s) << endl;
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution correctly finds the length of the longest substring without repeating characters. The solution uses a hash map to keep track of the last seen index of each character. If a character is seen again, the candidate checks if the character was seen after the start of the current substring. If so, the candidate updates the start of the substring to be one character after the last seen index of the repeated character. Otherwise, the candidate simply increments the length of the current substring. The candidate's solution correctly handles all edge cases and runs in O(n) time.

Evaluated at: 2022-11-25 00:16:03