-
Notifications
You must be signed in to change notification settings - Fork 0
/
17FindAllAnagramInAString.swift
59 lines (44 loc) · 1.54 KB
/
17FindAllAnagramInAString.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//
// ViewController.swift
// StockPrices
//
// Created by thailinh on 5/18/20.
// Copyright © 2020 thailinh. All rights reserved.
//
import UIKit
class Solution {
func findAnagrams(_ s: String, _ p: String) -> [Int] {
var results = [Int]()
let lengthOfP = p.count
let lengthOfS = s.count
if(lengthOfS==0||lengthOfS<lengthOfP){return results}
let newS = s.map { Int($0.asciiValue! - 97) }
let newP = p.map { Int($0.asciiValue! - 97) }
var markCharactersOfP = Array(repeating: 0, count: 26)
var markCharactersOfS = Array(repeating: 0, count: 26)
for index in 0..<p.count {
markCharactersOfP[newP[index]] += 1
markCharactersOfS[newS[index]] += 1
}
if compareArray(left: markCharactersOfS, right: markCharactersOfP){
results.append(0)
}
for index in (lengthOfP)..<lengthOfS{
markCharactersOfS[newS[index]] += 1
markCharactersOfS[newS[index - lengthOfP]] -= 1
if compareArray(left: markCharactersOfS, right: markCharactersOfP){
results.append(index - lengthOfP + 1)
}
}
return results
}
func compareArray (left : [Int], right : [Int]) -> Bool {
// left count == right count
for index in 0..<left.count{
if left[index] != right[index]{
return false
}
}
return true
}
}