-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy path290_WordPattern.swift
68 lines (63 loc) · 1.88 KB
/
290_WordPattern.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
60
61
62
63
64
65
66
67
68
//
// 290_WordPattern.swift
// HRSwift
//
// Created by yansong li on 2016-08-06.
// Copyright © 2016 yansong li. All rights reserved.
//
import Foundation
/**
Title:290 Word Pattern
URL: 7
Space: O(n)
Time: O(n)
*/
class WordPattern_Solution {
/// This is correct but with ugly logic
func wordPattern_initial(_ pattern: String, _ str: String) -> Bool {
var dict: [Character : String] = [:]
var wordIndexedDict: [String: Character] = [:]
let keys:[Character] = Array(pattern.characters)
let words = str.characters.split(separator: " ").map { String($0) }
guard words.count == keys.count else {
return false
}
for i in 0..<words.count {
let currentWord = words[i]
let currentKey: Character = keys[i]
if let existingWord = dict[currentKey] {
if currentWord != existingWord {
return false
}
} else {
if wordIndexedDict[currentWord] != nil {
return false
}
dict[currentKey] = currentWord
wordIndexedDict[currentWord] = currentKey
}
}
return true
}
func wordPattern(_ pattern: String, _ str: String) -> Bool {
var characterIndexedDict: [Character : String] = [:]
var wordIndexedDict: [String: Character] = [:]
let keys:[Character] = Array(pattern.characters)
let words = str.characters.split(separator: " ").map { String($0) }
guard words.count == keys.count else {
return false
}
for i in 0..<words.count {
let currentWord = words[i]
let currentKey: Character = keys[i]
if characterIndexedDict[currentKey] == nil && wordIndexedDict[currentWord] == nil {
characterIndexedDict[currentKey] = currentWord
wordIndexedDict[currentWord] = currentKey
// Logic is interesting.
} else if wordIndexedDict[currentWord] != currentKey {
return false
}
}
return true
}
}