Skip to content

Commit

Permalink
✨ Problem 003 Optimized Solution
Browse files Browse the repository at this point in the history
  • Loading branch information
jobearrr committed Jul 17, 2024
1 parent 13c5bbc commit 22e4fd6
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//
// LongestSubstringWithUniqueCharsOptimizedSlidingWindowSolution.swift
// LeetSwift
//
// Created by Jobert on 10/07/2024.
//

import Core
import Foundation
import Problems

final class LongestSubstringWithUniqueCharsOptimizedSlidingWindowSolution: LongestSubstringWithUniqueCharsDefinition {

func lengthOfLongestSubstring(_ s: String) -> Int {
var indexArray = Array(repeating: -1, count: 128)
var maxLength = 0
var start = 0

let chars = Array(s)

for i in 0..<chars.count {
guard let asciiValue = chars[i].asciiValue else { continue }
let asciiIndex = Int(asciiValue)

if indexArray[asciiIndex] != -1 {
start = max(start, indexArray[asciiIndex] + 1)
}

indexArray[asciiIndex] = i
maxLength = max(maxLength, i - start + 1)
}

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

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

final class LongestSubstringWithUniqueCharsOptimizedSlidingWindowSolutionTests: XCTestCase {

let solution: LongestSubstringWithUniqueCharsDefinition = LongestSubstringWithUniqueCharsOptimizedSlidingWindowSolution()

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

let output = solution.lengthOfLongestSubstring(input)

XCTAssertEqual(output, testData.expectedOutput)
}
}
}

extension LongestSubstringWithUniqueCharsOptimizedSlidingWindowSolutionTests: LongestSubstringWithUniqueCharsTestCaseProvider { }

0 comments on commit 22e4fd6

Please sign in to comment.