题目描述补充
题目:字符计数
给定一个字符串,统计并返回该字符串中每个字符出现的次数。字符的计数需要忽略大小写,并且结果应该按照字符的字典序进行排序。
示例
输入字符串:"Hello, World!"
输出(按字典序排序):
{
' ': 1,
',': 1,
'd': 1,
'e': 1,
'h': 1,
'l': 3,
'o': 2,
'r': 1,
'w': 1,
'!': 1
}
PHP 示例代码
<?php
function charCount($str) {
$counts = array();
$str = strtolower($str); // 忽略大小写
for ($i = 0; $i < strlen($str); $i++) {
$char = $str[$i];
if (ctype_alpha($char) || ctype_punct($char) || ctype_space($char)) { // 只考虑字母、标点符号和空格
if (!isset($counts[$char])) {
$counts[$char] = 0;
}
$counts[$char]++;
}
}
ksort($counts); // 按字典序排序
return $counts;
}
$input = "Hello, World!";
$result = charCount($input);
echo json_encode($result, JSON_PRETTY_PRINT);
?>
Python 示例代码
def char_count(s):
counts = {}
for char in s.lower(): # 忽略大小写
if char.isalnum() or char.isspace() or char.ispunct(): # 只考虑字母数字、空格和标点符号
if char not in counts:
counts[char] = 0
counts[char] += 1
return dict(sorted(counts.items())) # 返回按字典序排序的字典
input_str = "Hello, World!"
result = char_count(input_str)
print(result)
JavaScript 示例代码
function charCount(str) {
const counts = {};
str.toLowerCase().split('').forEach(char => {
if (/[a-z\d\s,.!?]/.test(char)) { // 只考虑字母、数字、空格、常见标点符号
if (!counts[char]) {
counts[char] = 0;
}
counts[char]++;
}
});
return Object.keys(counts).sort().reduce((acc, key) => {
acc[key] = counts[key];
return acc;
}, {}); // 按字典序排序后重新组装对象
}
const input = "Hello, World!";
const result = charCount(input);
console.log(JSON.stringify(result, null, 2));
附加信息
码小课网站中有更多关于算法和数据结构的内容分享给大家学习,涵盖了从基础到进阶的各种编程知识和技巧,欢迎大家访问学习。