题目要求
P1603题目链接
我们不如直接获取其平方数,这个就要基于HashMap啦,提前指定一下初始长度!
像10啊,20啊这种模完只剩00的,就不要了吧(他说是要最小的结果,开头0要去掉,那就显然……)
需要一个sort()的过程,基于内置函数就可以了!
遇到的两次WA第一次错的莫名其妙……
获取了测试数据2:
in
You are a three eight pig .
out
10964
始悟:最初的问题是没考虑到"a"其实也是1,所以就被坑了一次。 (这谁想得到啊)
第二次错在了set上
import java.util.*;
public class Main {
public static void main(String[] args) {
Map map = new HashMap(20);
map.put("one", "01");
map.put("a", "01");
map.put("two", "04");
map.put("three", "09");
map.put("four", "16");
map.put("five", "25");
map.put("six", "36");
map.put("seven", "49");
map.put("eight", "64");
map.put("nine", "81");
//map.put("ten", "00");
map.put("eleven", "21");
map.put("twelve", "44");
map.put("thirteen", "69");
map.put("fourteen", "96");
map.put("fifteen", "25");
map.put("sixteen", "56");
map.put("seventeen", "89");
map.put("eighteen", "24");
map.put("nineteen", "61");
//map.put("twenty", "00");
Set set = new TreeSet();
Scanner scanner = new Scanner(System.in);
String[] words = scanner.nextLine().trim().split("\\s+");
scanner.close();
for (String s : words) {
if (map.containsKey(s)) {
set.add(map.get(s));
}
}
if (set.isEmpty()) {
System.out.println(0);
}
StringBuilder str = new StringBuilder();
for (String s : set) {
str.append(s);
}
String result = str.toString();
if (result.startsWith("0")) {
result = result.substring(1);
}
System.out.println(result);
}
}
WA掉了第5个测试点,获取了其数据:
in
The a++ is a plus one .
out
101
始悟:set去重啊……(亏得我之前还专门用set给题目数据去重……)
那我们就用list然后sort()一下吧!
AC代码(Java语言描述)import java.util.*;
public class Main {
public static void main(String[] args) {
Map map = new HashMap(20);
map.put("one", "01");
map.put("a", "01");
map.put("two", "04");
map.put("three", "09");
map.put("four", "16");
map.put("five", "25");
map.put("six", "36");
map.put("seven", "49");
map.put("eight", "64");
map.put("nine", "81");
map.put("eleven", "21");
map.put("twelve", "44");
map.put("thirteen", "69");
map.put("fourteen", "96");
map.put("fifteen", "25");
map.put("sixteen", "56");
map.put("seventeen", "89");
map.put("eighteen", "24");
map.put("nineteen", "61");
List list = new ArrayList();
Scanner scanner = new Scanner(System.in);
String[] words = scanner.nextLine().trim().split("\\s+");
scanner.close();
for (String s : words) {
if (map.containsKey(s)) {
list.add(map.get(s));
}
}
if (list.isEmpty()) {
System.out.println(0);
}
StringBuilder str = new StringBuilder();
list.sort(Comparator.naturalOrder());
for (String s : list) {
str.append(s);
}
String result = str.toString();
if (result.startsWith("0")) {
result = result.substring(1);
}
System.out.println(result);
}
}