Skip to content

Instantly share code, notes, and snippets.

@NickHung1982
Created September 5, 2017 17:40
Show Gist options
  • Save NickHung1982/4e52db1055cf87a145d27e6c59914bd8 to your computer and use it in GitHub Desktop.
Save NickHung1982/4e52db1055cf87a145d27e6c59914bd8 to your computer and use it in GitHub Desktop.
//把每個要比較的字sort後比較, 如果相同就放在一起 直到巡覽完全部再存到outPutAr 最後再一起輸出
func groupAnagrams(_ strs: [String]) -> [[String]] {
var outPutAr = [[String]]()
var compareAr = Set(strs)
while compareAr.count > 0 {
let SameAr = returnSameAr(Array(compareAr))
outPutAr.append(SameAr) //將處理完後的陣列存入 outPutAr
compareAr.subtract(SameAr) //移除已經加過的陣列元素
}
return outPutAr
}
func returnSameAr(_ strs:[String]) -> [String] {
var tempAr = [String]()
for index in 0...strs.count - 1 {
if tempAr.count == 0 {
tempAr.append(strs[0])
continue
}else{
let sortedStr = String(strs[index].characters.sorted())
if sortedStr == String(strs[0].characters.sorted()) {
tempAr.append(strs[index])
}
}
}
return tempAr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment