Longest Substring Without Repeating Characters
💻 coding

Longest Substring Without Repeating Characters

1 min read 249 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to find the length of the longest substring without repeating characters in a given string.
  • 2Examples illustrate that 'abc' from 'abcabcbb' and 'wke' from 'pwwkew' are valid longest substrings.
  • 3The optimal solution uses a sliding window approach with a time complexity of O(n) and space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to find the length of the longest substring without repeating characters in a given string."

Longest Substring Without Repeating Characters

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

Example 1:

Input: "abcabcbb"

Output: 3

Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: "bbbbb"

Output: 1

Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"

Output: 3

Explanation: The answer is "wke", with the length of 3.

Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.Medium
{
 class LengthOfLongestSubstringSolution
 {
 public void execute()
 {
 int res = LengthOfLongestSubstring("abcabcbb");
 }
 public int LengthOfLongestSubstring(string s)
 {
 if (s=="")
 {
 return 0;
 }

 int max = 0;
 for (int i = 0; i < s.Length; i++)
 {
 int len = 1;
 var dict = new Dictionary<char, int>();
 dict.Add(s[i], 1);
 for (int j = i+1; j < s.Length; j++)
 {
 if (dict.ContainsKey(s[j]))
 {
 break;
 }
 else
 {
 len++;
 dict.Add(s[j], 1);
 }
 }
 if (max < len)
 {
 max = len;
 }
 }
 
 return max;
 }
 }
}

Time Complexity: O(n^2)

Space Complexity: O(n)

Using Sliding Window :

public int LengthOfLongestSubstringBySlidingWindow(string s)
 {
 int max = 0; 
 int start = 0;
 int end;
 var hashSet = new HashSet<char>();
 for (int i = 0; i < s.Length; i++)
 {
 if (hashSet.Contains(s[i]))
 { 
 while (s[start] != s[i])
 {
 hashSet.Remove(s[start]);
 start++;
 }
 start++;
 }
 else
 { 
 hashSet.Add(s[i]);
 if (max < hashSet.Count)
 {
 max = hashSet.Count;
 }
 }
 }
 return max;
 }

Time complexity: O(n)

Space complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 18 April 2020 · 1 min read · 249 words

Part of AskGif Blog · coding

You might also like