Vibe.ai
article thumbnail
๋ฐ˜์‘ํ˜•

โ“๋ฌธ์ œ

๋ฌธ์ž์—ด์„ ์ž…๋ ฅ๋ฐ›์•„ ๋ฌธ์ž์—ด์„ ๊ตฌ์„ฑํ•˜๋Š” ๊ฐ ๋ฌธ์ž(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ํšŒ๋งŒ ๋Œ๊ณ ๋„ ํ’€์ˆ˜์žˆ๋‹ค.

๋ฐ˜์‘ํ˜•
profile

Vibe.ai

@hai02y

ํฌ์ŠคํŒ…์ด ์ข‹์•˜๋‹ค๋ฉด "์ข‹์•„์š”โค๏ธ" ๋˜๋Š” "๊ตฌ๋…๐Ÿ‘๐Ÿป" ํ•ด์ฃผ์„ธ์š”!