Longest Substring Without Repeating Characters LeetCode

You can visit LeetCode Problem by clicking the Below Title.

Longest Substring Without Repeating Characters

Solution

				
					class Solution {
 public:
  int lengthOfLongestSubstring(string s) {
    int ans = 0;
    vector<int> count(128);

    for (int l = 0, r = 0; r < s.length(); ++r) {
      ++count[s[r]];
      while (count[s[r]] > 1)
        --count[s[l++]];
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};

				
			

Explanation

the provided code implements a function lengthOfLongestSubstring in C++ that calculates the length of the longest substring without repeating characters in a given string. It utilizes a sliding window approach and maintains two pointers to track the boundaries of the current substring.

By incrementing the count of each character and adjusting the boundaries of the substring when a character is repeated, the code ensures that only substrings with unique characters are considered. The length of the longest valid substring is continuously updated and returned as the final result.

It is important to include the necessary header files (<iostream> and <vector>) in order for the code to compile successfully.

				
					class Solution {
  public int lengthOfLongestSubstring(String s) {
    int ans = 0;
    int[] count = new int[128];

    for (int l = 0, r = 0; r < s.length(); ++r) {
      ++count[s.charAt(r)];
      while (count[s.charAt(r)] > 1)
        --count[s.charAt(l++)];
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}

				
			

Explanation

The provided code calculates the length of the longest substring without any repeating characters in a given string. It does so by using two pointers, l and r, to track the start and end of the current substring. The count array is used to keep track of the count of characters encountered so far. The algorithm iterates over the string and updates the ans variable with the maximum length found.

				
					class Solution:
  def lengthOfLongestSubstring(self, s: str) -> int:
    ans = 0
    count = collections.Counter()

    l = 0
    for r, c in enumerate(s):
      count[c] += 1
      while count[c] > 1:
        count[s[l]] -= 1
        l += 1
      ans = max(ans, r - l + 1)

    return ans

				
			

Explanation

The code uses the sliding window approach to efficiently find the length of the longest substring without repeating characters. It maintains a sliding window defined by the left and right pointers and updates the length of the longest substring as it iterates over the characters of the input string. The code has been fixed by importing the collections module to avoid an error.

Sharing Is Caring:

Leave a Comment