-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSherlockAndTheValidString.swift
48 lines (40 loc) · 1.23 KB
/
SherlockAndTheValidString.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
//
// SherlockAndTheValidString.swift
// HackerRank
//
// Created by Chaewan Park on 2020/07/14.
// Copyright © 2020 Chaewan Park. All rights reserved.
//
import Foundation
class SherlockAndTheValidString: Solution {
func run() {
isValid(s: "aabbcd") // NO
isValid(s: "aabbccddeefghi") // NO
isValid(s: "abcdefghhgfedecba") // YES
}
func isValid(s: String) {
let labeled = zip(s, Array(repeating: 1, count: s.count))
let hashed = Dictionary(labeled, uniquingKeysWith: +)
let values = hashed.values
let labeledValues = zip(values, Array(repeating: 1, count: values.count))
let valueCount = Dictionary(labeledValues, uniquingKeysWith: +)
if valueCount.count == 1 {
print("YES")
return
}
if valueCount.count > 2 {
print("NO")
return
}
let numbers = valueCount.sorted(by: <)
if numbers[0].key == 1 && numbers[0].value == 1 {
print("YES")
return
}
if (numbers[1].key - numbers[0].key) == 1 && numbers[1].value == 1 {
print("YES")
return
}
print("NO")
}
}