[Swift]LeetCode186. 翻转字符串中的单词 II $ Reverse Words in
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) 16 { 17 while (left < right) 18 { 19 var t:Character = s[left] 20 s[left] = s[right] 21 s[right] = t 22 left += 1 23 right -=1 24 } 25 } 26 } 27 28 extension String { 29 //subscript函数可以检索数组中的值 30 //直接按照索引方式截取指定索引的字符 31 subscript (_ i: Int) -> Character { 32 //读取字符 33 get {return self[index(startIndex,offsetBy: i)]} 34 35 //修改字符 36 set 37 { 38 var str:String = self 39 var index = str.index(startIndex,offsetBy: i) 40 str.remove(at: index) 41 str.insert(newValue,at: index) 42 self = str 43 } 44 } 45 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |