Java机试题:字符串按照指定规则排序
描述
编写一个程序,将输入字符串中的字符按如下规则排序。
规则 1 :英文字母从 A 到 Z 排列,不区分大小写。
如,输入: Type 输出: epTy
规则 2 :同一个英文字母的大小写同时存在时,按照输入顺序排列。
如,输入: BabA 输出: aABb
规则 3 :非英文字母的其它字符保持原来的位置。
思路
1.将输入的字符串拆分为两类,字母类和非字母类。
2.字母类进行忽略大小写类型进行排序,用于保证同一个英文字母的大小写同时存在时,按照输入顺序排列。
3.对于非字母类的字符,需要记录原始的位置。
4.将排序好的字母类和记录了非字母类位置的两部分合并,输出结果。
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Scanner; import javax.script.ScriptEngineManager; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNextLine()) { String str = sc.nextLine(); // 字母类型的集合 ListcharTypes = new ArrayList (); // 非字母类型的集合 List charNoEns = new ArrayList (); for (int i = 0; i < str.length(); i++) { String charInfo = str.substring(i,i+1); CharType charType = new CharType(); charType.setCharInfo(charInfo); charType.setPosition(i); if(charInfo.matches("[A-Za-z]")) { charTypes.add(charType); } else { charNoEns.add(charType); } } // 字符串排序,比较大小,忽略大小写,同字母大小写保持原来前后顺序 Collections.sort(charTypes,new Comparator (){ @Override public int compare(CharType o1, CharType o2) { return o1.getCharInfo().compareToIgnoreCase(o2.getCharInfo()); } }); // 结果字符串 StringBuffer strs = new StringBuffer(); CharType charNoEn = new CharType(); int charTypeCount = 0; // 结果集合长度为总长度 for (int i = 0; i < charTypes.size() + charNoEns.size(); i++) { // 判断当前位置是否有非字母类型 final int curPos = i; charNoEn = charNoEns.stream().filter(o-> o.getPosition() == curPos).findFirst().orElse(null); // 有非字母,保持原有位置 if(charNoEn != null) { strs.append(charNoEn.getCharInfo()); } else { // 字母。则使用排序后的位置,需注意的是:需要使用计数变量来 strs.append(charTypes.get(charTypeCount).getCharInfo()); charTypeCount++; } } System.out.println(strs.toString()); } } public static class CharType { private String charInfo; // 字符 private int position; // 输入时的位置 public String getCharInfo() { return charInfo; } public void setCharInfo(String charInfo) { this.charInfo = charInfo; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } } }