LeetCode 0003. Longest Substring Without Repeating Characters Solution Java | Python | C/C++ | JavaScripts | Go | Rust ++

CoderIndeed
0
0003. Longest Substring Without Repeating Characters

Description

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

 

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3. Note that "bca" and "cab" are also correct answers.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

 

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.

Solutions

Solution 1: Sliding Window

We can use two pointers l and r to maintain a sliding window that always satisfies the condition of having no repeating characters within the window. Initially, both l and r point to the first character of the string. We use a hash table or an array of length 128 called cnt to record the number of occurrences of each character, where cnt[c] represents the number of occurrences of character c.

Next, we move the right pointer r one step at a time. Each time we move it, we increment the value of cnt[s[r]] by 1, and then check if the value of cnt[s[r]] is greater than 1 within the current window [l, r]. If it is greater than 1, it means there are repeating characters within the current window, and we need to move the left pointer l until there are no repeating characters within the window. Then, we update the answer ans = max(ans, r - l + 1).

Finally, we return the answer ans.

The time complexity is O(n), where n is the length of the string. The space complexity is O(|Σ|), where Σ represents the character set, and the size of Σ is 128.

PythonJavaC++GoTypeScriptRustJavaScriptC#PHPSwiftKotlinC
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: cnt = Counter() ans = l = 0 for r, c in enumerate(s): cnt[c] += 1 while cnt[c] > 1: cnt[s[l]] -= 1 l += 1 ans = max(ans, r - l + 1) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !