1. 程式人生 > 實用技巧 >塗鴉問題(度小滿筆試)

塗鴉問題(度小滿筆試)

題目描述:

小A正在學畫畫,現在,線稿已經畫好了,只剩下塗色部分了。但是小A發現,他的顏料不夠了。每一塊顏料能塗一個色塊, 每一個色塊的顏色是事先決定好了的。由於顏料不夠,小A只能盡其所能來塗色。 如果一個色塊沒有了顏料,就不能塗色。現在,給你畫中需要的色塊顏色,和小A現在手上有的顏料,請你計算小A能塗多少個色塊。 輸入描述 輸入包含兩個字串,都僅包含大寫字母,每一種字母代表一種顏色。第一個字串S代表小A手上的顏料,第二個字串T代表畫需要的顏料。 1≤|S|,|T|≤1000 輸出描述 輸出包含一個數,即最多能塗多少個色塊。
樣例輸入
AAB
ABC
樣例輸出
2
提示

小A擁有兩個A顏料,一個B顏料,用了一個A顏料一個B顏料,總共塗了兩個色塊。
 1 import java.util.HashMap;
 2 import java.util.Map;
 3 import java.util.Scanner;
 4 
 5 public class Main {
 6     public static void main(String[] args) {
 7         Scanner input = new Scanner(System.in);
 8         String str = input.nextLine();
 9         String obj = input.nextLine();
10         Map<Character, Integer> strMap = new
HashMap<Character, Integer>(); 11 Map<Character, Integer> objMap = new HashMap<Character, Integer>(); 12 13 for (int i = 0; i < str.length(); i++) { 14 char c = str.charAt(i); 15 if (strMap.containsKey(c)) { 16 int num = strMap.get(c);
17 strMap.put(c, ++num); 18 } else { 19 strMap.put(c, 1); 20 } 21 } 22 23 for (int i = 0; i < obj.length(); i++) { 24 char c = obj.charAt(i); 25 if (objMap.containsKey(c)) { 26 int num = objMap.get(c); 27 objMap.put(c, ++num); 28 } else { 29 objMap.put(c, 1); 30 } 31 } 32 int total = 0; 33 for (int i = 0; i < str.length(); i++) { 34 char c = str.charAt(i); 35 int pre = strMap.get(c); 36 if (objMap.containsKey(c)){ 37 int next = objMap.get(c); 38 if (pre == next) { 39 total += next; 40 41 } else if (pre > next) { 42 total += next; 43 44 } else { 45 total += pre; 46 } 47 strMap.put(c, 0); 48 objMap.put(c, 0); 49 } 50 51 } 52 System.out.println(total); 53 } 54 }