在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Write a function that takes a string as input and returns the string reversed. Example 1: Input: Example 2: Input: 编写一个函数,其作用是将输入的字符串反转过来。 示例 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 }
|
请发表评论