package com.study.algorithm;
public class Demo {
public static void main(String[] args) {
// 将该数组翻转 输出 person a am I,要求空间复杂度为O(1),不考虑时间复杂度
char[] words = {'I', ' ', 'a', 'm', ' ', 'a', ' ', 'p', 'e', 'r', 's', 'o', 'n'};
print(words);
// 执行方法
revert(words);
print(words);
}
private static void revert(char[] arr) {
// 将数组全部反转
reverseArr(arr, -1, -1);
int start = 0, end = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == ' ') {
end = i - 1;
reverseArr(arr, start, end);
start = i + 1;
}
}
}
/**
* 反转数组
* @param arr
* @param index
* @param to
*/
private static void reverseArr(char[] arr, int index, int to) {
System.out.println("index = " + index + " , to = " + to);
index = index < 0 ? 0 : index;
to = to < 0 ? arr.length - 1 : to;
for (int i = 0; i <= (to - index) / 2; i++) {
char temp = arr[index + i];
arr[index + i] = arr[to - i];
arr[to - i] = temp;
}
}
private static void print(char[] arr) {
for (char c : arr) {
System.out.print(c);
}
System.out.println();
}
}