Advertisement
Alexxik

Untitled

Mar 19th, 2024 (edited)
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.87 KB | None | 0 0
  1. // Найти анаграмму S в тексте Text
  2.  
  3. func findAnagrams(_ text: String, _ s: String) -> [Int] {
  4.     let text: [String] = Array(text).map{String($0)}
  5.     let s: [String] = Array(s).map{String($0)}
  6.  
  7.     if s.count > text.count {
  8.         return []
  9.     }
  10.  
  11.     var result: [Int] = []
  12.     var diff: [String: Int] = [:]
  13.  
  14.     for i in 0..<s.count {
  15.         diff[s[i], default: 0] += 1
  16.     }
  17.     var l = 0
  18.     var r = 0
  19.  
  20.     while r < text.count {
  21.  
  22.         if diff[ text[r] ] ?? 0 > 0 {
  23.            
  24.             diff[ text[r] ]! -= 1
  25.             if r - l + 1 == s.count {
  26.                 result.append(l)
  27.             }
  28.             r += 1
  29.         } else if l == r {
  30.             l += 1
  31.             r += 1
  32.         } else {
  33.             diff[ text[l] ]! += 1
  34.             l += 1
  35.         }
  36.     }
  37.     return result
  38. }
  39.  
  40. findAnagrams("baeidbaooo", "ab")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement