题目
344. 反转字符串[1]
描述
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[]
的形式给出。
不要给另外的数组分配额外的空间,你必须**原地[2]修改输入数组**、使用 O(1) 的额外空间解决这一问题。
你可以假设数组中的所有字符都是 ASCII[3] 码表中的可打印字符。
示例 1:
输入:["h","e","l","l","o"]输出:["o","l","l","e","h"]
示例 2:
输入:["H","a","n","n","a","h"]输出:["h","a","n","n","a","H"]
解题思路
- 若数组长度为偶数,则遍历数组长度的一半;若数组长度为奇数,则遍历数组长度的一半向下取整;
- 然后定义一个临时变量,用临时变量将字符数组前后元素交换位置;
实现
代码语言:javascript复制package string;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
* Version : 1.0
* Author : cunyu
* Email : cunyu1024@foxmail.com
* Website : https://cunyu1943.github.io
* Date : 2020/3/19 22:35
* Project : LeetCode
* Package : string
* Class : ThreeHundredFortyFour
* Desc : 344.反转字符串
*/
public class ThreeHundredFortyFour {
public static void main(String[] args) {
ThreeHundredFortyFour threeHundredFortyFour = new ThreeHundredFortyFour();
char[] s = {'1', '3', '9', '7'};
threeHundredFortyFour.reverseString(s);
System.out.println(Arrays.toString(s));
}
/**
* 反转字符串
* @param s
*/
public void reverseString(char[] s) {
for (int i = 0; i < (int) (s.length / 2); i ) {
char tmp = s[i];
s[i] = s[s.length - 1 - i];
s[s.length - 1 - i] = tmp;
}
}
}
参考资料
[1]
344. 反转字符串: https://leetcode-cn.com/problems/reverse-string/
[2]
原地: https://baike.baidu.com/item/原地算法
[3]
ASCII: https://baike.baidu.com/item/ASCII