Skip to content

Commit 6c38ebe

Browse files
authored
string/reverse-string
1 parent 9026442 commit 6c38ebe

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

string/reverse-string.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
Write a function that reverses a string. The input string is given as an array of characters s.
3+
4+
You must do this by modifying the input array in-place with O(1) extra memory.
5+
6+
7+
8+
Example 1:
9+
10+
Input: s = ["h","e","l","l","o"]
11+
Output: ["o","l","l","e","h"]
12+
Example 2:
13+
14+
Input: s = ["H","a","n","n","a","h"]
15+
Output: ["h","a","n","n","a","H"]
16+
17+
18+
Constraints:
19+
20+
1 <= s.length <= 105
21+
s[i] is a printable ascii character.
22+
*/
23+
24+
package main
25+
26+
import "fmt"
27+
28+
func main() {
29+
reverseString([]byte(string([]rune{'h', 'e', 'l', 'l', 'o'})))
30+
}
31+
32+
func reverseString(s []byte) {
33+
start, end := 0, len(s)-1
34+
for start <= end {
35+
tmp := s[start]
36+
s[start] = s[end]
37+
s[end] = tmp
38+
39+
start++
40+
end--
41+
}
42+
43+
fmt.Println(string(s))
44+
}

0 commit comments

Comments
 (0)