LeetCode 题解工作台
检查平衡字符串
给你一个仅由数字 0 - 9 组成的字符串 num 。如果偶数下标处的数字之和等于奇数下标处的数字之和,则认为该数字字符串是一个 平衡字符串 。 如果 num 是一个 平衡字符串 ,则返回 true ;否则,返回 false 。 示例 1: 输入: num = "1234" 输出: false 解释…
1
题型
10
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们可以用一个长度为 的数组 来记录偶数下标和奇数下标的数字之和,然后遍历字符串 ,根据下标的奇偶性将数字加到对应的位置上,最后判断 是否等于 即可。 时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个仅由数字 0 - 9 组成的字符串 num。如果偶数下标处的数字之和等于奇数下标处的数字之和,则认为该数字字符串是一个 平衡字符串。
如果 num 是一个 平衡字符串,则返回 true;否则,返回 false。
示例 1:
输入:num = "1234"
输出:false
解释:
- 偶数下标处的数字之和为
1 + 3 = 4,奇数下标处的数字之和为2 + 4 = 6。 - 由于 4 不等于 6,
num不是平衡字符串。
示例 2:
输入:num = "24123"
输出:true
解释:
- 偶数下标处的数字之和为
2 + 1 + 3 = 6,奇数下标处的数字之和为4 + 2 = 6。 - 由于两者相等,
num是平衡字符串。
提示:
2 <= num.length <= 100num仅由数字 0 - 9 组成。
解题思路
方法一:模拟
我们可以用一个长度为 的数组 来记录偶数下标和奇数下标的数字之和,然后遍历字符串 ,根据下标的奇偶性将数字加到对应的位置上,最后判断 是否等于 即可。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
class Solution:
def isBalanced(self, num: str) -> bool:
f = [0, 0]
for i, x in enumerate(map(int, num)):
f[i & 1] += x
return f[0] == f[1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) as each character is visited once. Space complexity is O(1) because only two sum variables are needed, independent of string length. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checks understanding of string iteration and index handling.
- question_mark
Evaluates ability to implement a numeric check without unnecessary data structures.
- question_mark
Observes awareness of edge cases, such as strings with minimal length or equal digits.
常见陷阱
外企场景- error
Confusing index parity, summing wrong positions for even vs odd indices.
- error
Converting characters incorrectly, e.g., adding ASCII values instead of integers.
- error
Using extra arrays or lists unnecessarily, increasing space complexity.
进阶变体
外企场景- arrow_right_alt
Balance check on strings with alphabetic characters representing numeric values.
- arrow_right_alt
Check balanced condition for longer numeric strings with length up to 10^5.
- arrow_right_alt
Modify the definition to consider weighted sums for even and odd positions.