Created
September 5, 2017 17:40
-
-
Save NickHung1982/4e52db1055cf87a145d27e6c59914bd8 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
//把每個要比較的字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