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

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-fqzuqzhe-hd.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

Example 1:github

Input: "hello"
Output: "olleh" 

Example 2:微信

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

編寫一個函數,其做用是將輸入的字符串反轉過來。app

示例 1:函數

輸入: "hello"
輸出: "olleh"

示例 2:spa

輸入: "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 }

24mscode

 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 }

28mshtm

 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 }

36msblog

 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 }
相關文章
相關標籤/搜索