# LeetCode算法题-Most Common Word（Java实现）

### 01 看题和准备

paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."

banned = ["hit"]

• 1 <= paragraph.length <= 1000.

• 0 <= banned.length <= 100.

• 1 <= banned[i].length <= 10.

• 答案是唯一的，并用小写字母书写（即使它在段落中的出现可能有大写符号，即使它是一个专有名词。）

• 段落只包含字母，空格或标点符号!?',;.。

• 没有连字符或带连字符的单词。

• 单词仅由字母组成，从不包含撇号或其他标点符号。

### 02 第一种解法

public String mostCommonWord(String paragraph, String[] banned) {
String str = paragraph.toLowerCase();
str = str.replace(",", " ");  //!?',;.
str = str.replace("!", " ");
str = str.replace("?", " ");
str = str.replace("'", " ");
str = str.replace(";", " ");
str = str.replace(".", " ");
for (String s : banned) {
str = str.replaceAll(s, "");
}
String[] arr = str.split(" ");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String ss : arr) {
if (!ss.trim().isEmpty()) {
map.put(ss.trim(), map.getOrDefault(ss.trim(), 0)+1);
}
}
int max = Integer.MIN_VALUE;
String result = "";
for (Map.Entry<String,Integer> entry : map.entrySet()) {
if (entry.getValue() > max) {
max = entry.getValue();
result = entry.getKey();
}
}
return result;
}

### 03 第二种解法

public String mostCommonWord2(String paragraph, String[] banned) {
if (paragraph.trim().isEmpty()) {
return "";
}
Map<String, Integer> map = new HashMap<String, Integer>();
int start = 0, end = 0, n = paragraph.length();
while (end < n) {
if (Character.isLetter(paragraph.charAt(end))) {
end++;
} else {
if (end > 0 && Character.isLetter(paragraph.charAt(end-1))) {
String str = paragraph.substring(start, end).toLowerCase();
start = end;
map.put(str, map.getOrDefault(str, 0)+1);
}
start++;
end++;
}
}
if (start < end) {
String str = paragraph.substring(start, end).toLowerCase();
map.put(str, map.getOrDefault(str, 0)+1);
}
for (String s : banned) {
if (map.containsKey(s)) {
map.remove(s);
}
}
int max = Integer.MIN_VALUE;
String result = "";
for (Map.Entry<String,Integer> entry : map.entrySet()) {
if (entry.getValue() > max) {
max = entry.getValue();
result = entry.getKey();
}
}
return result;
}

### 04 第三种解法

public String mostCommonWord3(String paragraph, String[] banned) {
if (paragraph.trim().isEmpty()) {
return "";
}
String[] arr = paragraph.toLowerCase().split("\\W+");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String ss : arr) {
map.put(ss, map.getOrDefault(ss, 0)+1);
}
for (String s : banned) {
if (map.containsKey(s)) {
map.remove(s);
}
}
String result = "";
for (String key : map.keySet()) {
if (result == "") {
result = key;
} else if (map.get(key) > map.get(result)) {
result = key;
}
}
return result;
}

### 05 小结

posted @ 2019-04-30 14:42  程序员小川  阅读(...)  评论(... 编辑 收藏