import Foundation
func isInDict(_ word: String, _ dict: [String]) -> Bool {
return dict.contains(word)
}
func wordBreak(_ str: String, _ result: String, _ dict: [String]) {
let strSize = str.count
for i in 1...strSize {
let subStr = String(str.prefix(i))
if isInDict(subStr, dict) {
if i == strSize {
print(result + subStr)
return
}
let remaining = String(str.dropFirst(i))
wordBreak(remaining, result + subStr + " ", dict)
}
}
}
let str = "butterflyplaybasketballwithbags"
let dict = ["butterfly", "basketball", "bagpiper", "and", "play",
"with", "butter", "fly", "basket", "ball", "bags"]
wordBreak(str, "", dict)
/*
run:
butter fly play basket ball with bags
butter fly play basketball with bags
butterfly play basket ball with bags
butterfly play basketball with bags
*/