In this post, we will solve the Longest Substring Without Repeating Characters LeetCode Solution.
Problem Statement:
Given a string s
, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
Longest Substring Without Repeating Characters LeetCode Solution
Problem solution in JavaScript programming:
function lengthOfLongestSubstring(s) { let maxLength = 0, start = 0, end = 0; const charIndexMap = {}; while (end < s.length) { const char = s[end]; if (charIndexMap[char] >= start) { start = charIndexMap[char] + 1; } charIndexMap[char] = end; maxLength = Math.max(maxLength, end - start + 1); end++; } return maxLength; }
Problem solution in Python programming:
def lengthOfLongestSubstring(self, s): max_length = 0 start = 0 char_index_map = {} for end in range(len(s)): char = s[end] if char in char_index_map and char_index_map[char] >= start: start = char_index_map[char] + 1 char_index_map[char] = end max_length = max(max_length, end - start + 1) return max_length
Problem solution in C++ programming:
int lengthOfLongestSubstring(std::string s) { int maxLength = 0; int start = 0; std::unordered_map<char, int> charIndexMap; for (int end = 0; end < s.length(); end++) { char c = s[end]; if (charIndexMap.count(c) && charIndexMap[c] >= start) { start = charIndexMap[c] + 1; } charIndexMap[c] = end; maxLength = std::max(maxLength, end - start + 1); } return maxLength; }
Leave a Reply