Last active
August 4, 2019 00:33
-
-
Save piyush23dez/0733be76387982b5d61c162a989bc5fe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
medium.com/@sorenlind/three-ways-to-enumerate-the-words-in-a-string-using-swift-7da5504f0062 | |
extension String { | |
func words() -> [String] { | |
let range = self.startIndex..<self.endIndex | |
var words = [String]() | |
self.enumerateSubstrings(in: range, options: NSString.EnumerationOptions.byWords) { (substring, _, _, _) -> () in | |
words.append(substring ?? "") | |
} | |
return words | |
} | |
} | |
func mostCommonWord(bannedWords: [String], paragraph: String) -> String { | |
let hashset = Set(bannedWords) | |
var hashmap = [String:Int]() | |
let cleanString = Array(paragraph.lowercased().words()) | |
print(cleanString) | |
for word in cleanString { | |
if !hashset.contains(word) { | |
if let val = hashmap[word] { | |
hashmap[word] = val + 1 | |
} else { | |
hashmap[word] = 1 | |
} | |
} | |
} | |
var result = "" | |
for key in hashmap.keys { | |
if result == "" || hashmap[key]! > hashmap[result]! { | |
result = key | |
} | |
} | |
return result | |
} | |
let word = mostCommonWord(bannedWords: ["hit"], paragraph: "Bob hit a ball, the hit BALL flew far after it was hit.") | |
print(word) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment