1. Subject content
Write a function whose role is to reverse the input string. The input string is given in the form of a character array char[].
Don't allocate extra space to another array, you must modify the input array in place and use O(1) extra space to solve this problem.
You can assume that all characters in the array are printable characters in the ASCII code table.
Example 1 :
输入:["h","e","l","l","o"]
输出:["o","l","l","e","h"]
Example 2 :
输入:["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]
2. Topic analysis
This is a fairly simple classic problem, directly on the problem solution: use double pointer to reverse the string.
Suppose the input string is ["h","e","l","l","0"]
- Define left and right to point to the first and last elements respectively
- When left <right, swap.
- The exchange is complete, left++, right–
- Until left == right
The specific process is shown in the figure below:
Three, code implementation
func reverseString(s []byte) {
left := 0
right := len(s) - 1
for left < right {
s[left], s[right] = s[right], s[left]
left++
right--
}
}