Advertisement
Alexxik

Untitled

Sep 11th, 2023 (edited)
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.94 KB | None | 0 0
  1. // MARK: - 438. Find All Anagrams in a String
  2.  
  3. func findAnagrams1(_ s: String, _ p: String) -> [Int] {
  4.     var p = Array(p).map{String($0)}
  5.     var s = Array(s).map{String($0)}
  6.     var pCount = [String:Int]()
  7.     var sCount = [String:Int]()
  8.  
  9.     if p.count > s.count {return []}
  10.    
  11.     for i in 0..<p.count {
  12.         pCount[p[i], default: 0] += 1
  13.         sCount[s[i], default: 0] += 1
  14.     }
  15.    
  16.     var result: [Int]
  17.     if pCount == sCount {
  18.         result = [0]
  19.     } else {
  20.         result = []
  21.     }
  22.    
  23.     var l = 0
  24.     var r = p.count
  25.    
  26.     while r < s.count {
  27.        
  28.         sCount[ s[r], default: 0 ] += 1
  29.         sCount[ s[l], default: 0 ] -= 1
  30.        
  31.         if sCount[ s[l] ] == 0 {
  32.             sCount[ s[l] ] = nil
  33.         }
  34.         l += 1
  35.         r += 1
  36.        
  37.         if sCount == pCount {
  38.             result.append(l)
  39.         }
  40.     }
  41.     return result
  42. }
  43.  
  44. findAnagrams1("cbaebabacd", "ba")
  45.  
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement