题目:
编写一个反转字符串的函数。输入字符串作为字符数组char[]给出。
不要为另一个数组分配额外的空间,您必须使用O(1)额外内存修改输入数组。
您可以假设所有字符都由可打印的ascii字符组成。
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.
Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"] Input: ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"]
方法:
前后调换
代码:
class Solution {
public void reverseString(char[] s) {
char temp = ' ';
for(int i=0;i<s.length/2;i++) {
temp = s[i];
s[i] = s[s.length-1-i];
s[s.length-1-i] = temp;
}
}
}