• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
coding trails

coding trails

hello wisconsin!!!

  • Cards of Power

Longest Substring Without Repeating Characters

October 7, 2024 by schildawg Leave a Comment

Description

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

Tests

As always, let’s start out with the tests:

/// The answer is 'abc', with the length of 3.
///
test 'Example 1';
begin
    AssertEqual(3, LongestSubstring('abcabcbb'));
end

/// The answer is 'b', with the length of 1.
///
test 'Example 2';
begin
    AssertEqual(1, LongestSubstring('bbbbb'));
end

/// 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.
///
test 'Example 3';
begin
    AssertEqual(3, LongestSubstring('pwwkew'));
end

 

Solution

This is a medium level LeetCode question.  Coding it is simple if you know the concept of the “sliding window.”

function LongestSubstring(S : String) : Integer;
var
   Start, Finish, TheMax : Integer := 0;
   TheSet : Set := Set();

begin
    while Finish < Length(S) do
    begin
        if Not TheSet.Contains(S[Finish]) then
            begin
                TheSet.Add(S[Finish]);        
                Finish := Finish + 1;
                
                TheMax := Max(TheSet.Length, TheMax);
            end
        else
            begin
                TheSet.Remove(S[Start]);
                Start := Start + 1;
            end 
    end
    Exit TheMax;
end

Use a Set to keep track of the unique characters.  Start out with the “window” start and finish at the beginning of the String, and loop until the finish is at the end of the String.  If the character at the end of the window is not in the Set, add it and move the end by one.  If not, remove the character at the start of the window from the Set and move the start by one.

When the end of the window is at the end of window, return the largest number of characters the Set contained.  (Every time you add a character, set the max to the length of the Set, if it is larger than the previous max.

Filed Under: LeetCode, Programming

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Recent Posts

  • Modernization Code Converter
  • Paradigm Shift
  • LeetCode
  • Longest Substring Without Repeating Characters
  • The Big Bang
  • Add Two Numbers
  • The Word
  • Two Sum

Archives

  • June 2025
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • April 2024

Copyright © 2025 · Genesis Sample on Genesis Framework · WordPress · Log in

  • Cards of Power