题目描述补充
题目:括号得分
给定一个包含圆括号、方括号和花括号的字符串,要求计算该字符串的得分。规则如下:
- 每个左括号(
(
、[
、{
)与其对应的右括号()
、]
、}
)配对成功,则得1分。 - 如果一个左括号找不到对应的右括号,或者一个右括号找不到对应的左括号,则视为无效括号,不计入得分。
- 字符串中还可能包含其他非括号字符,这些字符应被忽略。
示例:
- 输入:"(())",输出:2
- 输入:"()[]{}",输出:3
- 输入:"(]", 输出:0(因为括号不匹配)
- 输入:"{[]}", 输出:2
PHP 示例代码
function calculateScore($s) {
$stack = [];
$score = 0;
$mapping = [')' => '(', ']' => '[', '}' => '{'];
for ($i = 0; $i < strlen($s); $i++) {
$char = $s[$i];
if (in_array($char, ['(', '[', '{'])) {
array_push($stack, $char);
} elseif (isset($mapping[$char]) && end($stack) === $mapping[$char]) {
array_pop($stack);
$score++;
}
}
return $score;
}
// 测试
echo calculateScore("(())") . "\n"; // 输出 2
echo calculateScore("()[]{}") . "\n"; // 输出 3
echo calculateScore("(]") . "\n"; // 输出 0
echo calculateScore("{[]}") . "\n"; // 输出 2
Python 示例代码
def calculateScore(s):
stack = []
score = 0
mapping = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in ['(', '[', '{']:
stack.append(char)
elif char in mapping and stack and stack[-1] == mapping[char]:
stack.pop()
score += 1
return score
# 测试
print(calculateScore("(())")) # 输出 2
print(calculateScore("()[]{}")) # 输出 3
print(calculateScore("(]")) # 输出 0
print(calculateScore("{[]}")) # 输出 2
JavaScript 示例代码
function calculateScore(s) {
let stack = [];
let score = 0;
const mapping = {')': '(', ']': '[', '}': '{'};
for (let char of s) {
if (['(', '[', '{'].includes(char)) {
stack.push(char);
} else if (mapping[char] && stack[stack.length - 1] === mapping[char]) {
stack.pop();
score++;
}
}
return score;
}
// 测试
console.log(calculateScore("(())")); // 输出 2
console.log(calculateScore("()[]{}")); // 输出 3
console.log(calculateScore("(]")); // 输出 0
console.log(calculateScore("{[]}")); // 输出 2
码小课网站中有更多关于算法和数据结构的内容分享给大家学习,欢迎访问并深入探索。