File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments