이 문제는 단순한 구현 문제로 문제에 대한 세부 조건을 잘 읽지 않으면 틀릴 수 있는 문제이다.
public static String isValid(String s) {
// Write your code here
HashMap<Character, Integer> map = new HashMap<>();
pushCharToMap(s, map);
return checkValidation(map);
}
public static void pushCharToMap(String s, HashMap<Character, Integer> map) {
for(int i = 0; i < s.length(); i++) {
map.putIfAbsent(s.charAt(i), 0);
map.computeIfPresent(s.charAt(i),(k,v) -> v+1);
}
}
public static String checkValidation(HashMap<Character, Integer> map) {
TreeMap<Integer, Integer> sizeMap = new TreeMap<>();
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
sizeMap.putIfAbsent(entry.getValue(), 0);
sizeMap.computeIfPresent(entry.getValue(), (k, v) -> v + 1);
}
//All alphabet count is 1 case
if (sizeMap.size() == 1) return "YES";
//alphabet's counts are over 2 case
if (sizeMap.keySet().size() > 2) return "NO";
//alphabet's counts are 2 and has only one alphabet
else if(sizeMap.firstEntry().getKey() == 1 && sizeMap.firstEntry().getValue() == 1) return "YES";
//alphabet's counts are 2 and can delete one alphabet
else if(checkHasOnlyOneCharacterSize(sizeMap) && (sizeMap.firstEntry().getKey() + 1 == sizeMap.lastEntry().getKey())) return "YES";
else return "NO";
}
public static boolean checkHasOnlyOneCharacterSize(TreeMap<Integer, Integer> sizeMap) {
return sizeMap.entrySet().stream().anyMatch(entry->entry.getValue() == 1);
}
}
https://www.hackerrank.com/challenges/sherlock-and-valid-string/
'문제풀이' 카테고리의 다른 글
[프로그래머스] 보석쇼핑 (0) | 2022.10.03 |
---|---|
[HakerRank] Climbing the Leaderboard (0) | 2022.10.02 |
[LeetCode] 187. Repeated DNA Sequences Java (0) | 2021.06.18 |
[Leetcode] Game of Life Java (0) | 2021.06.18 |
[프로그래머스] 압축 java (0) | 2021.05.06 |