FuzzBuzz算法问题
java实现输入一个字符串,5:hogera 3:piyo 2:huga 30 按空格分隔为map。
例如,key为数字5,value为字符串hogera,
当最后的数字满足,30=532时,按照key的从小到达的顺序拼接字符串输出hugapiyohogera
当最后的数字数字满足其中一个key时,使出对应的value。
都不满足,直接输出最后一个数字
输入:5:hogera 3:piyo 2:huga 30
输出:hugapiyohogera
输入:5:hogera 3:piyo 2:huga 3
输出:piyo
输入:5:hogera 3:piyo 2:huga 33
输出:33
** TreeMap可以实现自动排序
import java.util.*;
public class Chocolate {
public static void main(String[] args) {
String[] lines = getStdin();
Map<Integer, String> map = new TreeMap<>();
//分割空格得到字符串数组
String[] parts = lines[0].split("\\s+");
//遍历字符串数组存入map,除了最后一位
int lastNum = Integer.parseInt(parts[parts.length - 1]);
for (int j = 0; j < parts.length - 1; j++) {
String[] keyValue = parts[j].split(":");
int key = Integer.parseInt(keyValue[0]);
String value = keyValue[1];
map.put(key, value);
}
Set<Integer> set = map.keySet();
StringBuilder result = new StringBuilder();
int product = 1;
for (int num : set) {
product *= num;
}
if (product == lastNum) {
for (int key : set) {
result.append(map.get(key));
}
System.out.println(result);
return;
}
boolean flag = false;
for (int key : set) {
if (key == lastNum) {
System.out.println(map.get(key));
flag = true;
break;
}
}
if (!flag) {
System.out.println(lastNum);
}
}
private static String[] getStdin() {
Scanner scanner = new Scanner(System.in);
ArrayList<String> lines = new ArrayList<>();
while (scanner.hasNext()) {
lines.add(scanner.nextLine());
}
return lines.toArray(new String[lines.size()]);
}
}