package huawei;
import java.util.Scanner;
/**
* 将输入的字符串按照规定重新排序,如果字符串长度为奇数, 则中间的字符保持不变, 中间字符左侧降序排列, 右侧字符按照升序排列,
如果字符串长度为偶数,则左半侧字符降序排列,右半侧字符则按照升序排列
例如,
输入:ab5de
输出:ba5de
输入:abde
输出:bade
* @author USER
*
*/
public class CharacterSort {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String string = in.nextLine();
System.out.println(sort(string));
}
private static String sort(String string) {
// TODO Auto-generated method stub
char[] ch = string.toCharArray();
int len = ch.length;
for (int i = 0; i < len/2-1; i++) {
for (int j = i+1; j < len/2; j++) {
if (ch[i]<ch[j]) {
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
}
}
}
if (len % 2 ==0) {
for (int i = len/2; i < len-1; i++) {
for (int j = i+1; j < len; j++) {
if (ch[i]>ch[j]) {
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
}
}
}
}else {
for (int i = len/2+1; i < len-1; i++) {
for (int j = i+1; j < len; j++) {
if (ch[i]>ch[j]) {
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
}
}
}
}
return new String(ch);
}
}
华为机试---字符串的规定重新排序
最新推荐文章于 2024-08-07 07:02:35 发布