LeetCode 3. Longest Substring Without Repeating Characters

Here is my solution in PHP to this problem.

class Solution {

    /**
     * @param String $s
     * @return Integer
     */
    function lengthOfLongestSubstring($s) {
        $n = strlen($s);
        $ans = 0;
        $i = 0;
        $j = 0;

        $arr = [];

        while ($i < $n && $j < $n) {
            if (!in_array($s[$j], $arr)) {
                $arr[] = $s[$j++];
                $ans = max($ans, $j-$i);
            } else {
                array_splice($arr, 0, 1);
                $i++;
            }
        }


        return $ans;
    }
}

And here is solution JavaScript based on this Udemy lesson:

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    if (s.length <= 1) return s.length;

    const seenChars = {};
    let i=0, longest=0;

    for (let j=0; j<s.length; j++) {
        const currentChar = s[j];
        const currentCharIndex = seenChars[currentChar];

        if (currentCharIndex>=i) {
            i = currentCharIndex+1;
        }

        longest = Math.max(longest, j-i+1);
        seenChars[currentChar] = j;
    }

    return longest;
};

Published on