在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. 给定输入字符串,逐字反转字符串。单词被定义为非空格字符序列。 输入字符串不包含前导或后缀空格,并且单词总是由一个空格分隔。 例如, 给定 s = "the sky is blue", 返回 "blue is sky the".。 您能在不分配额外空间的情况下就地完成吗? 1 class Solution { 2 func reverseWords(_ s: inout String){ 3 var left:Int = 0 4 for i in 0...s.count 5 { 6 if i == s.count || s[i] == " " 7 { 8 reverse(&s, left, i - 1) 9 left = i + 1 10 } 11 } 12 reverse(&s, 0, s.count - 1) 13 } 14 15 func reverse(_ s: inout String,_ left:Int,_ right:Int) 16 { 17 var left = left 18 var right = right 19 while (left < right) 20 { 21 var t:Character = s[left] 22 s[left] = s[right] 23 s[right] = t 24 left += 1 25 right -= 1 26 } 27 } 28 } 29 30 extension String { 31 //subscript函数可以检索数组中的值 32 //直接按照索引方式截取指定索引的字符 33 subscript (_ i: Int) -> Character { 34 //读取字符 35 get {return self[index(startIndex, offsetBy: i)]} 36 37 //修改字符 38 set 39 { 40 var str:String = self 41 var index = str.index(startIndex, offsetBy: i) 42 str.remove(at: index) 43 str.insert(newValue, at: index) 44 self = str 45 } 46 } 47 }
|
请发表评论