3. Longest Substring Without Repeating Characters #34
Answered
by
mah-shamim
mah-shamim
asked this question in
Q&A
-
Given a string Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Answered by
mah-shamim
Jul 28, 2024
Replies: 1 comment
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 3. Longest Substring Without Repeating Characters <?PHP
function lengthOfLongestSubstring($s) {
$n = strlen($s);
$maxLength = 0;
$charIndexMap = [];
$start = 0;
for ($end = 0; $end < $n; $end++) {
$char = $s[$end];
// If the character is already in the map and its index is within the current window
if (isset($charIndexMap[$char]) && $charIndexMap[$char] >= $start) {
// Move the start right after the last occurrence of current character
$start = $charIndexMap[$char] + 1;
}
// Update the latest index of the character
$charIndexMap[$char] = $end;
// Update the maximum length of substring found
$maxLength = max($maxLength, $end - $start + 1);
}
return $maxLength;
}
// Example usage:
echo lengthOfLongestSubstring("abcabcbb") . "\n"; // Output: 3
echo lengthOfLongestSubstring("bbbbb") . "\n"; // Output: 1
echo lengthOfLongestSubstring("pwwkew") . "\n"; // Output: 3
echo lengthOfLongestSubstring("") . "\n"; // Output: 0
?> Explanation:
This solution efficiently finds the desired substring length with a time complexity of O(n), where n is the length of the input string. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
basharul-siddike
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To solve this problem, we can follow these steps:
Initialize Variables:
maxLength
to store the maximum length of substring found.charIndexMap
to store the last index of each character encountered.start
to represent the starting index of the current window.Sliding Window:
end
representing the end of the current window.s[end]
is already in thecharIndexMap
and its index is greater than or equal tostart
, move thestart
tocharIndexMap[s[end]] + 1
.charIndexMap
with the current index ofs[end]
.end - start + 1
) and updatemaxLength
if it's larger than the previously recorde…