forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseString.swift
37 lines (35 loc) · 967 Bytes
/
ReverseString.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Question Link: https://leetcode.com/problems/reverse-string/
* Primary idea: Use reverse() to help reverse the string
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class ReverseString {
func reverseString(s: String) -> String {
return String(s.characters.reverse())
}
}
/**
* Question Link: https://leetcode.com/problems/reverse-string/
* Primary idea: Using two iterators, one at the beginning, moving forward, another at the end moving backward.
* Swap them each time they move.
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class Solution {
func reverseString(s: String) -> String {
var chars: [Character] = [Character](s.characters)
var b = 0
var e = chars.count - 1
while b < e {
let tmp = chars[b]
chars[b] = chars[e]
chars[e] = tmp
b += 1
e -= 1
}
return String(chars)
}
}