题解 | #字符串排序#
字符串排序
http://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
解题思路:
把输入的字符串分成两部分,第一部分是包含字母的列表,对这部分进行排序;( 题目第一个要求sort排序,第二个要求保留大小写先后顺序用LinkedList)
List<Character> charList = new LinkedList<>();
第二部分记录非字母的下标
List<Integer> otherInexs = new ArrayList<>();字母列表排序完成后,合并还原字符串。(第三个要求非字母要还原到原来的位置,记录index,合并时还原回去)
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { String s = sc.nextLine(); System.out.println(sortString(s)); } } private static String sortString(String s) { List<Character> charList = new LinkedList<>(); char[] charArr = s.toCharArray(); int len = charArr.length; List<Integer> otherInexs = new ArrayList<>(); //非字母的下标,合并还原时要用 for (int i = 0; i < len; i++) { if (Character.isLetter(charArr[i])) { charList.add(charArr[i]); } else { otherInexs.add(i); } } charList.sort(new Comparator<Character>() {//也可以用Collections.sort @Override public int compare(Character o1, Character o2) { return Character.toLowerCase(o1) - Character.toLowerCase(o2); } }); StringBuffer sb = new StringBuffer(); // char[] merge = new char[len]; //排序后重新合并 int charIndex = 0; for (int i = 0; i < len; i++) { if (otherInexs.contains(i)) { // merge[i] = charArr[i]; sb.append(charArr[i]); } else { // merge[i] = charList.get(charIndex); sb.append(charList.get(charIndex)); charIndex ++; } } return sb.toString(); } }