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


    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址:https://www.cnblogs.com/strengthen/p/10172134.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?


    给定输入字符串,逐字反转字符串。单词被定义为非空格字符序列。

    输入字符串不包含前导或后缀空格,并且单词总是由一个空格分隔。

    例如,

    给定  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 }
  • 相关阅读:
    zookeeper历史版本下载
    RabbitMq集群搭建
    spring boot rabbitmq整合rabbitmq之消息持久化存储
    跨域
    Spring注入(IOC):
    AOP
    jsp自定义标签
    配置文件要注意的项
    线程
    URL转码
  • 原文地址:https://www.cnblogs.com/strengthen/p/10172134.html
Copyright © 2020-2023  润新知