SRM287Div2,250

この記事は約3分で読めます。

You will be given a String[] customerNames, containing a list of customer names extracted from a database. Your task is to report the customers that occur more than once in this list, and the number of occurrences for each of the repeated customers.

Your method should return the report as a String[]. Each element in this String[] should be of the form “NAME OCCURS“, where NAME is the name of one customer andOCCURS is the number of times his name occurs in customerNames. Sort the result in alphabetical order by customer name.

[java]

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CustomerStatistics {
public String[] reportDuplicates(String[] customerNames) {
Arrays.sort(customerNames);
//System.out.println(Arrays.toString(customerNames));
List<String> namelist = new ArrayList<String>();
int count=0;
for (int i = 0; i < customerNames.length-1; i++) {
if (customerNames[i].equals(customerNames[i+1])) {
count++;
}else{
if (count!=0) {
namelist.add(customerNames[i]+" "+(count+1));
}
count=0;
}
}
if (count!=0) {
namelist.add(customerNames[customerNames.length-1]+" "+(count+1));
}
String[] ans = (String[])namelist.toArray(new String[0]);
//System.out.println(Arrays.toString(ans));
return ans;
}
}

[/java]

コメント

タイトルとURLをコピーしました