Longest Substring Without Repeating Characters LeetCode Solution

Here, We see Longest Substring Without Repeating Characters problem Solution. This Leetcode problem done in many programming language like C++, Java, JavaScript, Python etc. with different approach.

Longest Substring Without Repeating Characters LeetCode Solution

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.

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.

C++ Solution ->

class Solution { public: int lengthOfLongestSubstring(string s) { int n = int(s.length()), res = 0; unordered_map<char, int> mp; for (int j = 0, i = 0; j < n; j++){ if(mp[s[j]] > 0) { i = max(mp[s[j]], i); } res = max(res, j - i + 1); mp[s[j]] = j + 1; } return res; } };
Code language: C++ (cpp)

Java Solution ->

public class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(), ans = 0; Map<Character, Integer> map = new HashMap<>(); // current index of character // try to extend the range [i, j] for (int j = 0, i = 0; j < n; j++) { if (map.containsKey(s.charAt(j))) { i = Math.max(map.get(s.charAt(j)), i); } ans = Math.max(ans, j - i + 1); map.put(s.charAt(j), j + 1); } return ans; } }
Code language: Java (java)

Python Solution ->

class Solution: def lengthOfLongestSubstring(self, s: str) -> int: n = len(s) ans = 0 # mp stores the current index of a character mp = {} i = 0 # try to extend the range [i, j] for j in range(n): if s[j] in mp: i = max(mp[s[j]], i) ans = max(ans, j - i + 1) mp[s[j]] = j + 1 return ans
Code language: Python (python)

Longest Substring Without Repeating Characters python solution, Longest Substring Without Repeating Characters java solution, Longest Substring Without Repeating Characters JavaScript solution, Longest Substring Without Repeating Characters C++ solution

Leave a Comment

Your email address will not be published.