Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - 340. Longest Substring with At Most K Distinct Characters
- // s = "eceba", k = 2
- // 3 --> "ece" which its length is 3
- // Словарь и скользящее окно. Словарь надо уменьшать и удалять ключ когда count == 0
- func lengthOflongestSubStringK(_ s: String, k: Int) -> Int {
- var s = Array(s)
- var lettersDict = [Character:Int]()
- var l = 0
- var longest = 0
- for r in 0..<s.count {
- lettersDict[s[r], default: 0] += 1
- while lettersDict.count > k {
- lettersDict[s[l]]! -= 1
- if lettersDict[s[l]] == 0 {
- lettersDict[s[l]] = nil
- }
- l += 1
- }
- longest = max(longest, r - l + 1)
- }
- return longest
- }
- lengthOflongestSubStringK("eceba", k: 2)
- lengthOflongestSubStringK("aabacccac", k: 2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement