LeetCode 3340.检查平衡字符串:模拟
【LetMeFly】3340.检查平衡字符串:模拟
力扣题目链接:https://leetcode.cn/problems/check-balanced-string/
给你一个仅由数字 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 组成。
解题方法:遍历求和
使用一个整型变量 c n t cnt cnt来统计结果即可。遍历字符串,遇到奇数下标则加上当前字符对应的数字,否则减去之。最终判断 c n t cnt cnt是否为 0 0 0。
- 时间复杂度 O ( l e n ( n u m ) ) O(len(num)) O(len(num))
- 空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C++
/*
* @Author: LetMeFly
* @Date: 2025-03-14 09:30:43
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-03-14 09:32:51
*/
class Solution {
public:
bool isBalanced(string num) {
int cnt = 0;
for (int i = 0; i < num.size(); i++) {
cnt += i % 2 ? (num[i] - '0') : -(num[i] - '0');
}
return cnt == 0;
}
};
Python
'''
Author: LetMeFly
Date: 2025-03-14 09:34:04
LastEditors: LetMeFly.xyz
LastEditTime: 2025-03-14 09:34:04
'''
class Solution:
def isBalanced(self, num: str) -> bool:
cnt = 0
for i, c in enumerate(num):
cnt += ord(c) - 48 if i % 2 else 48 - ord(c)
return cnt == 0
Java
/*
* @Author: LetMeFly
* @Date: 2025-03-14 09:35:26
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-03-14 09:35:26
*/
class Solution {
public boolean isBalanced(String num) {
int cnt = 0;
for (int i = 0; i < num.length(); i++) {
if (i % 2 == 0) {
cnt += num.charAt(i) - 48;
} else {
cnt -= num.charAt(i) - 48;
}
}
return cnt == 0;
}
}
Go
/*
* @Author: LetMeFly
* @Date: 2025-03-14 09:36:55
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-03-14 09:38:01
*/
package main
func isBalanced(num string) bool {
cnt := 0
for i, c := range num {
if i % 2 == 0 {
cnt += int(c) - 48
} else {
cnt -= int(c) - 48
}
}
return cnt == 0
}
同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~
千篇源码题解已开源