Advertisement
Alexxik

Untitled

Sep 15th, 2023 (edited)
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.89 KB | None | 0 0
  1. // MARK: - 340. Longest Substring with At Most K Distinct Characters
  2. // s = "eceba", k = 2
  3. // 3 --> "ece" which its length is 3
  4.  
  5. // Словарь и скользящее окно. Словарь надо уменьшать и удалять ключ когда count == 0
  6.  
  7. func lengthOflongestSubStringK(_ s: String, k: Int) -> Int {
  8.     var s = Array(s)
  9.     var lettersDict = [Character:Int]()
  10.     var l = 0
  11.     var longest = 0
  12.    
  13.     for r in 0..<s.count {
  14.        
  15.         lettersDict[s[r], default: 0] += 1
  16.        
  17.         while lettersDict.count > k {
  18.             lettersDict[s[l]]! -= 1
  19.             if lettersDict[s[l]] == 0 {
  20.                 lettersDict[s[l]] = nil
  21.             }
  22.             l += 1
  23.         }
  24.        
  25.         longest = max(longest, r - l + 1)
  26.     }
  27.     return longest
  28. }
  29.  
  30. lengthOflongestSubStringK("eceba", k: 2)
  31. lengthOflongestSubStringK("aabacccac", k: 2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement