Skip to content

Commit e478d43

Browse files
author
Yi Gu
committed
[String] add solution to Reverse String
1 parent df8accb commit e478d43

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

String/ReverseString.swift

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/reverse-string/
3+
* Primary idea: Two pointers, iterate the string and swap two characters each time
4+
*
5+
* Note: Swift does not have a way to access a character in a string with O(1),
6+
* thus we have to first transfer the string to a character array
7+
* Time Complexity: O(n), Space Complexity: O(n)
8+
*
9+
*/
10+
11+
class ReverseString {
12+
func reverseString(s: String) -> String {
13+
var left = 0
14+
var right = s.characters.count - 1
15+
var chars = [Character](s.characters)
16+
17+
while left < right {
18+
_swap(&chars, left, right)
19+
left += 1
20+
right -= 1
21+
}
22+
23+
return String(chars)
24+
}
25+
26+
private func _swap(inout chars:[Character], _ p: Int, _ q: Int) {
27+
var temp = chars[p]
28+
chars[p] = chars[q]
29+
chars[q] = temp
30+
}
31+
}

0 commit comments

Comments
 (0)