Reverse string
Title description: 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 for 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.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/reverse-string/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution one: array traversal
Traversal s, traversal order is0~s.length/2
, the firsti
value of the item ands.length-1-i
value of the item exchange. The s after the traversal is completed is the reversed string.
public class LeetCode_344 {
public static void reverseString(char[] s) {
for (int i = 0; i < s.length / 2; i++) {
// 第i项和第s.length-1-i项进行交换
char temp = s[i];
s[i] = s[s.length - 1 - i];
s[s.length - 1 - i] = temp;
}
}
public static void main(String[] args) {
char[] s = new char[]{'h', 'e', 'l', 'l', 'o'};
System.out.println("-----反转之前-----");
for (char c : s) {
System.out.print(c + " ");
}
System.out.println();
reverseString(s);
System.out.println("-----反转之后-----");
for (char c : s) {
System.out.print(c + " ");
}
}
}
[Daily Message] Every breakthrough is to achieve a better self.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。