๋ฐ์ํ
โ๋ฌธ์
๋ฌธ์์ด์ ์
๋ ฅ๋ฐ์ ๋ฌธ์์ด์ ๊ตฌ์ฑํ๋ ๊ฐ ๋ฌธ์(letter)๋ฅผ ํค๋ก ๊ฐ๋ HashMap์ ๋ฆฌํดํด์ผ ํฉ๋๋ค.
๊ฐ ํค์ ๊ฐ์ ํด๋น ๋ฌธ์๊ฐ ๋ฌธ์์ด์์ ๋ฑ์ฅํ๋ ํ์๋ฅผ ์๋ฏธํ๋ int ํ์
์ ๊ฐ์ด์ด์ผ ํฉ๋๋ค.
์ ๋ ฅ
์ธ์ 1 : str
String ํ์
์ ๊ณต๋ฐฑ์ด ์๋ ๋ฌธ์์ด
์ถ๋ ฅ
<Character, Integer> ํ์ ์ ์์๋ก ๊ฐ๋ HashMap์ ๋ฆฌํดํด์ผ ํฉ๋๋ค.
์์
โ๏ธCode
[์ฝ๋]
import java.util.*;
public class Solution {
public HashMap<Character, Integer> countAllCharacter(String str) {
//TODO..
int len = str.length();
HashMap<Character,Integer> hashMap = new HashMap<>();
if(len==0)return null;
for(int i=0;i<=len-1;i++){
char index = str.charAt(i);
if(hashMap.containsKey(index)){
int value = hashMap.get(index);
hashMap.put(index,value+1);
}else{
hashMap.put(index,1);
}
}
return hashMap;
}
}
๐ฅPlus
HashMap์ ๋ค๋ฃฐ๋ key์ value๋ฅผ ๋ฐ๋ก ์ ์ธํด์ ๋ค๋ฃฐ์๊ฐ์๋ชปํ๋ค.
for(int i=0;i<=len-1;i++){
char index = str.charAt(i); //index => key๋ก ์ฌ์ฉ
if(hashMap.containsKey(index)){
int value = hashMap.get(index); //value => value๋ก ์ฌ์ฉ
hashMap.put(index,value+1); //hashmap์ ํ ๋นํด์ฃผ๊ณ value๊ฐ์ ๋ํด์ค๋ค.
}else{
hashMap.put(index,1); //hashmap ์ด๊ธฐํ ๋ถ๋ถ
}
}
์ฒ์ํ๋ for๋ฌธ์ ์ค์ฒฉํด์ ํธ๋๋ฐฉ๋ฒ์ ์ป๋๋ฐ ์ด๋ ๊ฒํ๋ฉด for๋ฌธ์ 1ํ๋ง ๋๊ณ ๋ ํ์์๋ค.
๋ฐ์ํ