LeetCode 题解工作台

检查平衡字符串

给你一个仅由数字 0 - 9 组成的字符串 num 。如果偶数下标处的数字之和等于奇数下标处的数字之和,则认为该数字字符串是一个 平衡字符串 。 如果 num 是一个 平衡字符串 ,则返回 true ;否则,返回 false 。 示例 1: 输入: num = "1234" 输出: false 解释…

category

1

题型

code_blocks

10

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们可以用一个长度为 的数组 来记录偶数下标和奇数下标的数字之和,然后遍历字符串 ,根据下标的奇偶性将数字加到对应的位置上,最后判断 是否等于 即可。 时间复杂度 ,其中 为字符串 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个仅由数字 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 <= 100
  • num 仅由数字 0 - 9 组成。
lightbulb

解题思路

方法一:模拟

我们可以用一个长度为 22 的数组 ff 来记录偶数下标和奇数下标的数字之和,然后遍历字符串 nums\textit{nums},根据下标的奇偶性将数字加到对应的位置上,最后判断 f[0]f[0] 是否等于 f[1]f[1] 即可。

时间复杂度 O(n)O(n),其中 nn 为字符串 nums\textit{nums} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
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]
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

检查平衡字符串题解:String-driven solution … | LeetCode #3340 简单