微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Swift]LeetCode186. 翻转字符串中的单词 II $ Reverse Words in a String II

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             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 }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐