首页 > 专题系列 > Java解POJ > POJ 1520 Scramble Sort [解题报告] Java
2013
11-09

POJ 1520 Scramble Sort [解题报告] Java

Scramble Sort

问题描述 :

In this problem you will be given a series of lists containing both words and numbers. The goal is to sort these lists in such a way that all words are in alphabetical order and all numbers are in numerical order. Furthermore, if the nth element in the list is a number it must remain a number, and if it is a word it must remain a word.

输入:

The input will contain multiple lists, one per line. Each element of the list will be separated by a comma followed a space, and the list will be terminated by a period. The input will be terminated by a line containing only a single period.

输出:

For each list in the input, output the scramble sorted list, separating each element of the list with a comma followed by a space, and ending the list with a period.

样例输入:

0.
banana, strawberry, OrAnGe.
Banana, StRaWbErRy, orange.
10, 8, 6, 4, 2, 0.
x, 30, -20, z, 1000, 1, Y.
50, 7, kitten, puppy, 2, orangutan, 52, -100, bird, worm, 7, beetle.
.

样例输出:

0.
banana, OrAnGe, strawberry.
Banana, orange, StRaWbErRy.
0, 2, 4, 6, 8, 10.
x, -20, 1, Y, 30, 1000, z.
-100, 2, beetle, bird, 7, kitten, 7, 50, orangutan, puppy, 52, worm.

解题代码:

//* @author: [email protected]
import java.util.*;
public class Main
{
 public static void main(String[] args)
 {
  Scanner in=new Scanner(System.in);
  while(true)
   {
	String s=in.nextLine();
	if(s.equals("."))break;
	s=s.substring(0,s.length()-1);
	String[] arr=s.split(", ");
	int l=arr.length;
	int[] kk=new int[l];
	ArrayList< Integer> arrI=new ArrayList< Integer>();
	TreeMap< String,String> arrS=new TreeMap< String,String>();
	for(int i=0;i< l;i++)
	{
	  if(isNum(arr[i])){
	    arrI.add(Integer.parseInt(arr[i]));
	    kk[i]=1;
	   }
	   else arrS.put(arr[i].toLowerCase(), arr[i]);
	}
	Collections.sort(arrI);
	int w=0,q=0;
	for(int i=0;i< l;i++)
	{
	 if(kk[i]==1) System.out.print(arrI.get(w++));
	 else {
	  System.out.print(arrS.get(arrS.firstKey()));
	  arrS.remove(arrS.firstKey());
	 }
	  if(i!=l-1) System.out.print(", ");
	}
	System.out.println(".");
   }
 }

 public static boolean isNum(String str)
 {
  char w=str.charAt(0);
  if(w!='-'&&(w>57||w<48)) return false;
  for(int i=1;i< str.length();i++)
  {
	char c=str.charAt(i);
	if(c>57||c< 48) return false;
  }
  return true;
 }
}