在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a string For example: Given Given Hint:
给定的字符串S,回报所有的palindromic置换(没有duplicates)的信息。返回的列表,如果没有空palindromic -可以排列形式。 例如: 给定 给定 提示:
1 class Solution { 2 func generatePalindromes(_ s:String) -> [String]{ 3 var res:Set<String> = Set<String>() 4 var m:[Character:Int] = [Character:Int]() 5 var t:String = "" 6 var mid:String = "" 7 for a in s.characters 8 { 9 m[a] = 1 10 } 11 for (key, val) in m 12 { 13 if val % 2 == 1 14 { 15 mid.append(key) 16 } 17 var str:String = String() 18 for i in 0..<val/2 19 { 20 str.append(key) 21 } 22 t += str 23 if mid.count > 1 24 { 25 return [] 26 } 27 } 28 permute(&t, 0, mid,&res); 29 return Array(res) 30 } 31 32 func permute(_ t:inout String,_ start:Int,_ mid:String,_ res:inout Set<String>) 33 { 34 if start >= t.count 35 { 36 let str:String = String(t.reversed()) 37 res.insert(t + mid + str) 38 } 39 for i in start..<t.count 40 { 41 if i != start && t[i] == t[start] 42 { 43 continue 44 } 45 var temp:Character 46 temp = t[start] 47 t[start] = t[i] 48 t[i] = temp 49 50 permute(&t, start + 1, mid, &res) 51 52 temp = t[start] 53 t[start] = t[i] 54 t[i] = temp 55 } 56 } 57 } 58 59 extension String { 60 //subscript函数可以检索数组中的值 61 //直接按照索引方式截取指定索引的字符 62 subscript (_ i: Int) -> Character { 63 //读取字符 64 get {return self[index(startIndex, offsetBy: i)]} 65 66 //修改字符 67 set 68 { 69 var str:String = self 70 var index = str.index(startIndex, offsetBy: i) 71 str.remove(at: index) 72 str.insert(newValue, at: index) 73 self = str 74 } 75 } 76 }
|
请发表评论