Skip to content

Commit

Permalink
✨ Sliding Window solution for problem 003
Browse files Browse the repository at this point in the history
  • Loading branch information
jobearrr committed Jul 10, 2024
1 parent b2b9fb5 commit c2e0d15
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//
// LongestSubstringWithoutRepeatingCharactersSlidingWindowSolution.swift
// LeetSwift
//
// Created by Jobert on 10/07/2024.
//

import Core
import Foundation
import Problems

final class LongestSubstringWithoutRepeatingCharactersSlidingWindowSolution: LongestSubstringWithoutRepeatingCharactersDefinition {

func lengthOfLongestSubstring(_ s: String) -> Int {
var indexMap = [Character: Int]()
var maxLength = 0
var start = 0

for (i, char) in s.enumerated() {
if let lastIndex = indexMap[char], lastIndex >= start {
start = lastIndex + 1
}
indexMap[char] = i
maxLength = max(maxLength, i - start + 1)
}

return maxLength
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//
// LongestSubstringWithoutRepeatingCharactersSlidingWindowSolutionTests.swift
// LeetSwift
//
// Created by Jobert on 10/07/2024.
//

import XCTest
@testable import Problems
@testable import Solutions
@testable import TestSupport

final class LongestSubstringWithoutRepeatingCharactersSlidingWindowSolutionTests: XCTestCase {

let solution: LongestSubstringWithoutRepeatingCharactersDefinition = LongestSubstringWithoutRepeatingCharactersSlidingWindowSolution()

func testSolution() {
for testData in data {
let input = testData.input

let output = solution.lengthOfLongestSubstring(input)

XCTAssertEqual(output, testData.expectedOutput)
}
}
}

extension LongestSubstringWithoutRepeatingCharactersSlidingWindowSolutionTests: LongestSubstringWithoutRepeatingCharactersTestCaseProvider { }

0 comments on commit c2e0d15

Please sign in to comment.