문제
Most Common Word - LeetCode
Can you solve this real interview question? Most Common Word - Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and tha
leetcode.com
한 단락과 금지 단어들이 주어지면 금지 단어를 제외한 나머지 단어의 빈도를 세어 빈도가 높은 단어를 반환해야 합니다.
주어지는 단락의 단어는 대소문자를 구분하지 않습니다. 즉 param, Param, paRam, ParAm 등을 구분하지 않고 하나로 간주합니다.
금지 단어는 하나 이상 주어지며, 가장 많이 나타난 단어를 반환할 때는 소문자로 반환합니다.
풀이
- 주어진 단락에서 단어만 취급하기 위해 특수문제 제외, 대소문자를 구분하지 않으므로 소문자로 변경이 필요합니다.
- 주어진 단락에서 금지 단어를 제외해야 합니다.
- 가장 많이 나타난 단어를 알기 위해 단어마다 등장 횟수를 기록해야 합니다.
class Solution {
public String mostCommonWord(String paragraph, String[] banned) {
String afterInput = paragraph.toLowerCase().replaceAll("[^0-9a-zA-Z\\s]", " ");
for (String e : banned) {
afterInput = afterInput.replaceAll(e, "");
}
String[] ary = afterInput.split(" ");
Map<String, Integer> count = new HashMap<>();
int t;
for (String e : ary) {
if (e.equals("")) continue;
t = count.getOrDefault(e, 0) + 1;
count.put(e, t);
}
List<String> keySet = new ArrayList<>(count.keySet());
keySet.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return count.get(o2) - count.get(o1);
}
});
return keySet.get(0);
}
}
참고
- 문자열에서 특수문자를 제하기 위해 String 내장 메서드 replaceAll에 쓰일 정규표현식을 알아야 했습니다.
- 단어마다 등장 횟수를 기록할 때 Map을 사용했습니다. 아무것도 없는 Map에 단어를 추가할 때 Map의 메서드 contains와 getOrDefault를 알아야 했습니다.
- 최다 빈도의 단어를 알기 위해 Collections의 메서드 sort와 max, Comparator를 알아야 했습니다.
실패
- 띄어쓰기까지 글자 수를 셈했습니다.
- 문자열을 String 배열로 변경했을 때 띄어쓰기도 배열의 요소가 되어 띄어쓰기가 글자 수에 포함되었습니다.
- 특수문자 다음에는 띄어쓰기가 있다고 생각했습니다.