首先,我引用今天的问题:
---方向
给定字符串,返回字符串中最常用的字符。
---示例
maxChar(“ abcccccccd”)===“ c”
maxChar(“ apple 1231111”)===“ 1”
JavaScript:
<span style="color:#f8f8f2"><span style="color:#eff0f9"><code>function maxChar(str) {
const charMap = {};
let max = 0;
let maxChar = '';
for (let char of str) {
if (charMap[char]) {
charMap[char]++
} else {
charMap[char] = 1;
}
}
for (let char in charMap) {
if (charMap[char] > max) {
max = charMap[char];
maxChar = char;
}
}
return maxChar;
}
</code></span></span>
Stephen将第一个for循环重写为:
<span style="color:#f8f8f2"><span style="color:#eff0f9"><code> for (let char of str) {
charMap[char] = charMap[char] + 1 || 1;
}
</code></span></span>
这是可能的,因为anObject['nonexistentKey']
回报率undefined
,undefined + 1
回报率NaN
,这是falsy。
Python:
<span style="color:#f8f8f2"><span style="color:#eff0f9"><code>def max_char(str):
char_map = {}
max = 0
max_char = ''
for char in str:
char_map.setdefault(char, 0)
char_map[char] += 1
for char in char_map:
if char_map[char] > max:
max = char_map[char]
max_char = char
return max_char
</code></span></span>
在Python中,您不能char_map[char] += 1
像在JS中那样尝试,因为如果密钥不存在,它将抛出KeyError。
更简洁地说:
<span style="color:#f8f8f2"><span style="color:#eff0f9"><code>def max_char(str):
char_map = {}
for char in str:
char_map.setdefault(char, 0)
char_map[char] += 1
return max(char_map, key=char_map.get)
</code></span></span>
来源:https : //stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionarymax(char_map, key=char_map.get)
与相同max(char_map.keys(), key=char_map.get)
。key=char_map.get
需要在字典中找到值最大的(键,值)元组对。max({'a': 2, 'b': 1})
返回“ b”。
Java:
<span style="color:#f8f8f2"><span style="color:#eff0f9"><code>import java.util.HashMap;
import java.util.Map;
public static char maxChar2(String str) {
Map<Character, Integer> charMap = new HashMap<>();
for (char chr : str.toCharArray()) {
Integer chrCount = charMap.get(chr);
if (chrCount == null) {
chrCount = 0;
}
charMap.put(chr, chrCount + 1);
}
int max = 0;
char maxChar = '\0';
for (Map.Entry<Character, Integer> entry : charMap.entrySet()) {
int value = entry.getValue();
if (value > max) {
max = value;
maxChar = entry.getKey();
}
}
return maxChar;
}
</code></span></span>
使用 Stream:
<span style="color:#f8f8f2"><span style="color:#eff0f9"><code>public static char maxChar(String str) {
Map<Character, Long> charMap = str.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(
c -> c, Collectors.counting()));
return charMap.entrySet().stream()
.collect(Collectors.groupingBy(
Map.Entry::getValue,
TreeMap::new,
Collectors.mapping(
Map.Entry::getKey, Collectors.toList())))
.lastEntry()
.getValue()
.get(0);
}
</code></span></span>
return语句可以变得更简单:
<span style="color:#f8f8f2"><span style="color:#eff0f9"><code> return charMap.entrySet().stream()
.max(Map.Entry.comparingByValue())
.get()
.getKey();</code></span></span>