为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode344. 反转字符串 | Reverse String

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9763187.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Write a function that takes a string as input and returns the string reversed.

Example 1:

Input: "hello"
Output: "olleh"

Example 2:

Input: "A man, a plan, a canal: Panama"
Output: "amanaP :lanac a ,nalp a ,nam A"

编写一个函数,其作用是将输入的字符串反转过来。

示例 1:

输入: "hello"
输出: "olleh"

示例 2:

输入: "A man, a plan, a canal: Panama"
输出: "amanaP :lanac a ,nalp a ,nam A"

20ms
 1 class Solution {
 2     func reverseString(_ s: String) -> String {
 3         guard s.count > 1 else {
 4             return s
 5         }
 6 
 7         var chars = s.utf8CString
 8         var low = 0
 9         var high = chars.count - 2
10         while low < high {
11             chars.swapAt(low, high)
12             low += 1
13             high -= 1
14         }
15         return String(cString: Array(chars))
16     }
17 }

24ms

 1 class Solution {
 2     func reverseString(_ s: String) -> String {
 3         var index = s.endIndex
 4         var result = ""
 5 
 6         while index != s.startIndex {
 7             index = s.index(before: index)
 8             result.append(s[index])
 9         }
10         
11         return result
12     }
13 }

28ms

 1 class Solution {
 2     func reverseString(_ s: String) -> String{
 3         var startIndex = 0
 4         var endIndex = s.count-1
 5         var array = s.cString(using:.utf8)!
 6         while startIndex<endIndex {
 7             let char = array[startIndex]
 8             array[startIndex] = array[endIndex]
 9             array[endIndex] = char
10             startIndex+=1
11             endIndex-=1
12         }
13         return String.init(utf8String: array)!
14     }
15 }

36ms

 1 class Solution {
 2     func reverseString(_ s: String) -> String {
 3         var chars = s.cString(using: String.Encoding.utf8)!
 4         var left = 0
 5         var right = s.count - 1
 6         
 7         while left < right {
 8             
 9             let char = chars[left]
10             chars[left] = chars[right]
11             chars[right] = char
12             
13             left = left + 1
14             right = right - 1
15         }
16         
17         return String.init(utf8String: chars)!
18     }
19 }

 

posted @ 2018-10-09 21:53  为敢技术  阅读(575)  评论(0编辑  收藏  举报