[Swift]LeetCode186. 翻轉字串中的單詞 II $ Reverse Words in a String II
阿新 • • 發佈:2018-12-25
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?
給定輸入字串,逐字反轉字串。單詞被定義為非空格字元序列。
輸入字串不包含前導或字尾空格,並且單詞總是由一個空格分隔。
例如,
給定 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 ifi == 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 }