★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-pruclynf-md.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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?git
給定輸入字符串,逐字反轉字符串。單詞被定義爲非空格字符序列。github
輸入字符串不包含前導或後綴空格,而且單詞老是由一個空格分隔。數組
例如,微信
給定 s = "the sky is blue",函數
返回 "blue is sky the".。spa
您能在不分配額外空間的狀況下就地完成嗎?code
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 }