字符串排序输出
<p style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;"><span style="font-size: 18px;">已知字母序列【d, g, e, c, f, b, o, a】,请实现一个函数针对输入的一组字符串 input[] = {"bed", "dog", "dear", "eye"},按照字母顺序排序并打印。</span></p><p style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;"><span style="font-size: 18px;">本例的输出顺序为:dear, dog, eye, bed。</span></p><p style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;"><span style="font-size: 18px;">代码中两个compare函数,其中一个为本题要求的场景,另外一个适用于正常情况下任何字母的。但是不知为何,我打印出来的顺序是dog dear eye bed。。。</span></p><p style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;"><span style="font-size: 18px;">本题只需要定义一个比较函数再排序即可,也可以用<span style="font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px;">Arrays.sort(inputs, </span><span class="keyword" style="margin: 0px; padding: 0px; border: none; color: rgb(0, 102, 153); font-weight: bold; font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px;">new</span><span style="margin: 0px; padding: 0px; border: none; font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px;"> Comparator<String>(){ });用一个匿名内部类传递一个比较器进去,最后打印的时候<span style="font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px;"> System.out.println(Arrays.toString(inputs)); </span></span></span></p>
package test.find; import java.util.HashMap; import java.util.Map; public class findString { public static void main(String args[]){ String[] s={"bed", "dog", "dear", "eye"}; printString(s); } public static void printString(String[] s){ for(int i=1;i<s.length;i++){ for(int j=i;j>0;j--){ if(compare(s[j-1],s[j])){ String temp=s[j]; s[j]=s[j-1]; s[j-1]=temp; } if(compare(s[j],s[j-1])) break; } } for(String str:s){ System.out.println(str); } } /*public static boolean compare(String a,String b){ int len1=a.length(); int len2=b.length(); for(int i=0;i<(len1>len2?len2:len1);i++){ if((a.charAt(i)-b.charAt(i))>0) return true; else if((a.charAt(i)-b.charAt(i))<0) return false; continue; } return false; }*/ public static boolean compare(String a,String b){ Map<Character,Integer> map=new HashMap<Character,Integer>(); map.put('d', 1); map.put('g', 2); map.put('e', 3); map.put('c', 4); map.put('f', 5); map.put('b', 6); map.put('o', 7); map.put('a', 8); int len1=a.length(); int len2=b.length(); for(int i=0;i<(len1>len2?len2:len1);i++){ if((map.get(a.charAt(i))-map.get(b.charAt(i)))>0) return true; else if(map.get(a.charAt(i))-map.get(b.charAt(i))<0) return false; else continue; } return true; } }
每天进步一点点!