Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: [“h”,“e”,“l”,“l”,“o”]
Output: [“o”,“l”,“l”,“e”,“h”]
Example 2:
Input: [“H”,“a”,“n”,“n”,“a”,“h”]
Output: [“h”,“a”,“n”,“n”,“a”,“H”]
Ideas of solving a problem
This is an interesting problem.We can start with the problem.So what they want us to do is they want us to reverse the input string, so we can split the input string in half.The first character is interchanged with the last character.Because we don’t need any extra space, we just need 1 to swap with n, 2 to swap with n minus 1, and so on. The time complexity is O(n), and the space complexity is O(1). Memory consumption is 6.3 Mb.
Code
package main
import (
"fmt"
)
func main(){
arr1 := [] byte {'h','e','l','l','o'}
reverseString(arr1)
fmt.Println(arr1)
}
func reverseString(s []byte) {
for i:=0;i<len(s)/2;i++{
s[i], s[len(s)-i-1] = s[len(s)-i-1], s[i]
}
return
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-string