Advertisement
Alexxik

Untitled

Sep 12th, 2023 (edited)
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.79 KB | None | 0 0
  1. // MARK: - 443. String Compression
  2. // Сжать строку
  3.  
  4. func compress(_ chars: inout [Character]) -> Int {
  5.     // i - чтобы итерироваться по масиву
  6.     var i = 0
  7.     var r = 0
  8.     while i < chars.count {
  9.         var currentChar = chars[i]
  10.         var currentOccur = 0
  11.         while i < chars.count && chars[i] == currentChar {
  12.             currentOccur += 1
  13.             i += 1
  14.         }
  15.        
  16.         chars[r] = currentChar
  17.         r += 1
  18.        
  19.         if currentOccur > 1 {
  20.             let currOccurStr = String(currentOccur)
  21.             for num in currOccurStr {
  22.                 chars[r] = num
  23.                 r += 1
  24.             }
  25.         }
  26.     }
  27.     return r
  28. }
  29.  
  30. var a: [Character] = ["a","a","b","b","c","c","c","c"]
  31. compress(&a)
  32. print(a)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement