試題 算法訓練 奇變的字符串
資源限制
時間限制:1.0s 內存限制:256.0MB
問題描述
將一個字符串的奇數位(首位爲第0位)取出,將其順序弄反,再放回原字符串的原位置上。
如字符串"abcdefg",奇數位爲"bdf",順序弄反後爲"fdb",最後得到字符串"afcdebg"。
輸入格式
輸入共一行,爲一個字符串,字符串中無空格。
輸出格式
輸出共一行,爲一個字符串,即最後得到的字符串。
樣例輸入
abcdefg
樣例輸出
afcdebg
數據規模和約定
字符串長度不超過255.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
regroup(str);
}
public static void regroup(String str){
char[] chars = str.toCharArray();
char temp;
int end ;
if (chars.length % 2 == 0) {
end = chars.length-1;
}else {
end = chars.length-2;
}
for (int i = 0; i < (chars.length)/2; i++) {
if (i%2!=0){
temp = chars[i];
chars[i] = chars[end];
chars[end] = temp;
end-=2;
}
}
for (char aChar : chars) {
System.out.print(aChar);
}
}
}