天天看點

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

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

➤微信公衆号:山青詠芝(shanqingyongzhi)

➤部落格園位址:山青詠芝(https://www.cnblogs.com/strengthen/)

➤GitHub位址:https://github.com/strengthen/LeetCode

➤原文位址:https://www.cnblogs.com/strengthen/p/9763187.html 

➤如果連結不是山青詠芝的部落格園位址,則可能是爬取作者的文章。

➤原文已修改更新!強烈建議點選原文位址閱讀!支援作者!支援原創!

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

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 }      

轉載于:https://www.cnblogs.com/strengthen/p/9763187.html