HashMap和HashSet使用--統計字符出現的次數

題目描述:

小易有一些彩色的磚塊。每種顏色由一個大寫字母表示。各個顏色磚塊看起來都完全一樣。現在有一個給定的字符串s,s中每個字符代表小易的某個磚塊的顏色。小易想把他所有的磚塊排成一行。如果最多存在一對不同顏色的相鄰磚塊,那麼這行磚塊就很漂亮的。請你幫助小易計算有多少種方式將他所有磚塊排成漂亮的一行。(如果兩種方式所對應的磚塊顏色序列是相同的,那麼認爲這兩種方式是一樣的。)
例如: s = "ABAB",那麼小易有六種排列的結果:
"AABB","ABAB","ABBA","BAAB","BABA","BBAA"
其中只有"AABB"和"BBAA"滿足最多隻有一對不同顏色的相鄰磚塊。 


分析:統計字母出現次數

package problems_2017_08_23;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;

public class Problem_01_01 {
	
	public static void main(String[] args){
		Scanner scan=new Scanner(System.in);
		String str=scan.nextLine();
		//HashMap
		HashMap<Character, Integer> map=new HashMap<Character,Integer>();
		int count=0;
		for(int i=0;i<str.length();i++){
			char ch=str.charAt(i);
			if(!map.containsKey(ch)){
				map.put(ch, 1);
				count++;
			}else{
				map.put(ch, map.get(ch)+1);
			}
		}
		
		//HashSet
//		HashSet<Character> set=new HashSet<Character>();
//		int count=0;
//		for(int i=0;i<str.length();i++){
//			char ch=str.charAt(i);
//			if(!set.contains(ch)){
//				set.add(ch);
//				count++;
//			}
//		}
		
		if(count>2){
			System.out.println("0");
		}else if(count==2){
			System.out.println("2");
		}else{
			System.out.println(count);
		}
	}
	
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章