
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Length of Longest Substring Without Repeating Characters
From the given string input, use the sliding window technique by having 2 pointers i and j . both i and j will point to the same character in the string. Traverse through the string and add it to the list. If the repeated character is found then remove it from the list else append to the list.
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.
Time complexity − O(N)
Space complexity − O(N)
Example
public class Arrays{ public int LongestSubstringWithNoRepeatingCharacters(string s){ List<char> c = new List<char>(); int iPointer = 0; int jpointer = 0; int max = 0; while (jpointer < s.Length){ if (c.Contains(s[jpointer])){ c.Remove(s[iPointer]); iPointer++; } else{ max = Math.Max(c.Count(), max); c.Add(s[jpointer]); jpointer++; } } return max; } } static void Main(string[] args){ int res = s.LongestSubstringWithNoRepeatingCharacters("abcabcbb"); Console.WriteLine(res); }
Output
2
Advertisements