問題
給定一個字符串?dāng)?shù)組,將數(shù)組內(nèi)元素進行反轉(zhuǎn)重窟。需在當(dāng)前數(shù)組中原地交換。
輸入:"h","e","l","l","o"
輸出:"o","l","l","e","h"
思路
雙指針触创。
定義一個指針left指向數(shù)組頭部
定義一個指針right指向數(shù)組尾部
left不斷自增薪丁,right不斷自減。當(dāng)left小于right時衅澈,則交換指針在數(shù)組內(nèi)對應(yīng)元素键菱。
image.png
實現(xiàn)
public class ReverseString {
public static void main(String[] args) {
String[] chars = new String[]{"h","e","l","l","o"};
String[] result = doubleIndex(chars);
System.out.println(Arrays.toString(result));
}
//雙指針
private static String[] doubleIndex(String[] chars) {
int length = chars.length;
int left = 0;
int right = length-1;
while (left < right){
doubleIndexSwap(chars,left++,right--);
}
return chars;
}
private static void doubleIndexSwap(String[] chars, int left, int right) {
String temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
}
}
image.png