EEALL@ONCE
๐จ๐ป Map / toLowerCase/charAt/getOrDefault/Map.Entry/entrySet ๋ณธ๋ฌธ
algorithm๐จ๐ป
๐จ๐ป Map / toLowerCase/charAt/getOrDefault/Map.Entry/entrySet
์ฌ์ฃ์์ค 2023. 8. 21. 22:31728x90
๋ฌธ์ :
์ํ๋ฒณ ๋์๋ฌธ์๋ก ๋ ๋จ์ด๊ฐ ์ฃผ์ด์ง๋ฉด, ์ด ๋จ์ด์์ ๊ฐ์ฅ ๋ง์ด ์ฌ์ฉ๋ ์ํ๋ฒณ์ด ๋ฌด์์ธ์ง ์์๋ด๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค. ๋จ, ๋๋ฌธ์์ ์๋ฌธ์๋ฅผ ๊ตฌ๋ถํ์ง ์๋๋ค.
๋์ ๋ต :
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String line= s.nextLine().toUpperCase();
HashMap<Character,Integer> count= new HashMap<>();
for(int i=0; i<line.length();i++){
char c=line.charAt(i);
count.put(c,count.getOrDefault(c,0)+1);
}
char mostCommon = ' ';
int mostCount=0;
for(Map.Entry<Character,Integer> entry : count.entrySet()){
if(entry.getValue()>mostCount){
mostCommon=entry.getKey();
mostCount=entry.getValue();
}
}
int check=0;
for(Map.Entry<Character,Integer> entry : count.entrySet()) {
if (entry.getValue() == mostCount) {
check++;
}
}
if(check>1) System.out.println("?");
else System.out.println(mostCommon);
}
}
๋ฉ๋ชจ๋ฆฌ ์ถ์ ๋ฒ์ : HashMap -> ๋ฐฐ์ด
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String line = s.nextLine().toUpperCase();
int[] count = new int[26]; // ์ํ๋ฒณ ๊ฐ์๋งํผ ๋ฐฐ์ด ์์ฑ
for (char c : line.toCharArray()) {
if (Character.isAlphabetic(c)) { // ์ํ๋ฒณ์ธ ๊ฒฝ์ฐ์๋ง ์ฒ๋ฆฌ
count[c - 'A']++;
}
}
int maxCount = 0;
char mostCommon = ' ';
boolean isUnique = true;
for (int i = 0; i < 26; i++) {
if (count[i] > maxCount) {
maxCount = count[i];
mostCommon = (char) (i + 'A');
isUnique = true;
} else if (count[i] == maxCount) {
isUnique = false;
}
}
if (isUnique) {
System.out.println(mostCommon);
} else {
System.out.println("?");
}
}
}
728x90
'algorithm๐จโ๐ป' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐จโ๐ป์ ๋ ฅ๋ ๋จ์ด๊ฐ ํฐ๋ฆฐ๋๋กฌ์ธ์ง ํ์ธํ๋ Java ํ๋ก๊ทธ๋จ (0) | 2023.08.17 |
---|