给一个字符串,将其按照单词顺序进行反转

本文探讨如何将给定字符串按单词顺序反转,同时注意单词长度差异和空格处理。通过代码实现和时间复杂度分析,揭示了问题背后的逻辑与技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给一个字符串,将其按照单词顺序进行反转。

例如

  • 源字符串: “the sky is blue”
  • 反转后字符串:“blue is sky the”

需要注意的点

  • 每个单词长度不一样。
  • 空格需要特殊处理。

分析

  • 这道题目一看好简单,不就是反转字符串的翻版吗?是也不是
  • 先将整个字符串翻转,“the sky is blue” -> “eulb si yks eht”
  • 每个单词作为一个字符串单独翻转,“eulb si yks eht” -> “blue is sky the”

代码

	//字符串翻转
	fileprivate func charReverse<T>(_ chars: inout [T], _ start: Int, _ end: Int) {
      	var s = start, e = end
        while s < e {
            swap(&s, &e)
            s += 1
            e -= 1
        }
    }
    //单词顺序进行反转
   	func wordReverse(s: String?) -> String? {
        guard let s = s else {
            return nil
        }
        var chars = Array(s), start = 0
        charReverse(&chars, 0, chars.count - 1)
        for i in 0..<chars.count {
            if i == chars.count - 1 || chars[i + 1] == " " {
                charReverse(&chars, start, i)
                start = i + 2
            }
        }
        return String(chars)
    }

总结

时间复杂度 O(n)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值