題目連結
題意:
有多個單字與對應分數
之後有好幾組題目
每一組題目1~多行(.結尾)
統計題目中各單字出現次數
轉成分數並加總
如:
3 1
abc 2
def 3
gh 4
abc abc abc def gh gh gh gh gh
.
總和: 2*3 + 3*1 + 4*5 = 29
解法:
字典題,出動 HashMap
先將字典建好 (Key - Value, 字串對應數字)
讀題目時,逐個單字讀取
每個單字都去字典找,找到則計算分數統計
程式(Java):
題意:
有多個單字與對應分數
之後有好幾組題目
每一組題目1~多行(.結尾)
統計題目中各單字出現次數
轉成分數並加總
如:
3 1
abc 2
def 3
gh 4
abc abc abc def gh gh gh gh gh
.
總和: 2*3 + 3*1 + 4*5 = 29
解法:
字典題,出動 HashMap
先將字典建好 (Key - Value, 字串對應數字)
讀題目時,逐個單字讀取
每個單字都去字典找,找到則計算分數統計
程式(Java):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static void main(String args[]) { | |
Scanner sc = new Scanner(System.in); | |
HashMap<String, Integer> hm = new HashMap<String, Integer>(); | |
String tmp[] = sc.nextLine().split("\\s+"); | |
int m = Integer.valueOf(tmp[0]); | |
int n = Integer.valueOf(tmp[1]); | |
for (int i = 0; i < m; i++) { | |
String tmp2[] = sc.nextLine().split("\\s+"); | |
hm.put(tmp2[0], Integer.valueOf(tmp2[1])); | |
} | |
for (int i = 0; i < n; i++) { | |
int sum = 0; | |
String s = sc.nextLine(); | |
while (!s.equals(".")) { | |
String str[] = s.split("\\s+"); | |
for (String t: str) { | |
if (hm.containsKey(t)) | |
sum += hm.get(t); | |
} | |
s = sc.nextLine(); | |
} | |
System.out.println(sum); | |
} | |
} | |
} |
留言
張貼留言