浪淘金

public class Test {


/**
*
* 數組中數值組合成最小序列
* 例如:
* 輸入{12,23} 輸出1223 而不是2312
*
* 思路:
* 設定數組元素 A,B
* 如果AB<BA 那麼A<B,反過來也成立 如果A<B,那麼AB<BA
* 因此要組合最小序列 == 元素從小到大的排序組合
*/
private static void sort(int[] array){
int temp;
for(int i=1;i<array.length;i++){
for(int j=i;(j>0)&&(array[j]<array[j-1]);j--){
temp = array[j];
array[j]=array[j-1];
array[j-1]=temp;
}
}
String b="";
for(int a:array){
b +=a;
}
System.out.print(b);
}


/**
*
* 字母排序(其中包含大寫與小寫字母),要求大寫字母放在小寫字母后面
* 例如:
* 輸入"bbAAbacGBkKdffEfgk" 輸出"aAAbbbBcdEfffgGkkK"
*
* 思路:
* 1.取出字符串中大寫字母出現的次數,保存起來
* 2.把原始字符串中字符轉換成小寫字母進行從小到大排序
* 3.根據1中記錄大寫字母出現的次數,把排序好的字符數組中小寫字母替換成大寫字母
*/
private static void sortChar(String data){
// 找出所有大寫字母,並記錄出現的次數
Map<Character,Integer> map = new HashMap<Character,Integer>();
char[] m = data.toCharArray();
for(char temp:m){
if(temp>='A'&&temp<='Z'){
if(map.containsKey(temp)){
Integer count = map.get(temp);
map.put(temp, ++count);
}else{
map.put(temp, 1);
}
}
}

// 把所有字符轉換成小寫字母后排序,從小到大排序
char[] c = data.toLowerCase().toCharArray();
char temp;
for(int i=1;i<c.length;i++){
for(int j=i;(j>0)&&(c[j]<c[j-1]);j--){
temp = c[j];
c[j]=c[j-1];
c[j-1]=temp;
}
}

// 把排好序的字符數組中大寫字母替換回來
for(int i=c.length-1;i>0;i--){
if(map.containsKey((char)(c[i]-32))){
int a = map.get((char)(c[i]-32));
if(a>0){
map.put((char)(c[i]-32), --a);
}else if(a==0){
continue;
}
c[i]=(char)(c[i]-32);
}
}

System.out.print(c);
}

/**
* test
*/
public static void main(String[] args) {
sort(new int[]{51,49,36,29,10});
sortChar("bbAAbacGBkKdffEfgk");
}

}
發佈了113 篇原創文章 · 獲贊 0 · 訪問量 8550
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章