본문 바로가기
알고리즘

[Swift] LeetCode - 3. Longest Substring Without Repeating Characters

by 고고 2022. 2. 16.

문제: https://leetcode.com/problems/longest-substring-without-repeating-characters/

 

Longest Substring Without Repeating Characters - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

used 딕셔너리로 start ~ index 사이에 중복이 있는지 없는지 검사했습니다

import Foundation

class Solution {
    func lengthOfLongestSubstring(_ s: String) -> Int {
        var result = 0
        let array = Array(s)
        var used = [Character: Int]()
        var start = 0
        
        for (index, char) in s.enumerated() {
            if used[char] != nil && start <= used[char]! {
                start = used[char]! + 1
            } else {
                result = max(result, index - start + 1)
            }
            
            used[char] = index
        }
        
        return result
    }
}

댓글