Skip to content

Commit 7b329d0

Browse files
Merge pull request #41 from Aadhithya01/improve-reverse-string
Refactor: use []rune and added metadata for string reversal in Go
2 parents 2472aa4 + 786e977 commit 7b329d0

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

snippets/Basics/go/reverse_string.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,28 @@
55

66
// Reverse a string - placeholder in go
77

8+
// Time Complexity: O(n)
9+
// Space Complexity: O(n)
10+
811
package main
912

1013
import "fmt"
1114

12-
func reverseString(s string) string {
13-
// Convert the string to a byte slice since strings are immutable in Go.
14-
str := []byte(s)
15-
// Use two pointers to swap characters from start and end.
15+
// reverse_string reverses the input string and returns the reversed result.
16+
func reverse_string(s string) string {
17+
// Convert the string to a rune slice to support Unicode.
18+
str := []rune(s)
19+
// Use two pointers to swap runes from start and end.
1620
for i, j := 0, len(str)-1; i < j; i, j = i+1, j-1 {
1721
str[i], str[j] = str[j], str[i]
1822
}
19-
// Convert the reversed byte slice back to a string.
23+
// Convert the reversed rune slice back to a string.
2024
return string(str)
2125
}
2226

2327
func main() {
2428
// Input string
25-
input := "Hacktoberfest"
29+
input := "Hacktoberfest 🌍"
2630
// Print the reversed string
27-
fmt.Println(reverseString(input))
28-
}
31+
fmt.Println(reverse_string(input))
32+
}

0 commit comments

Comments
 (0)