
2026-03-03:相等子字符串分数。用go语言,给定一个只含小写字母的字符串 s。把每个字母替换为它在字母表中的序号(a→1, b→2, …, z→26),然后某段字符串的“分值”就是其所有字母序号之和。现在要判断能否在某个位置切开 s,使得左侧和右侧各自至少包含一个字符,且两边的分值相等。如果存在这样的切点,返回 true,否则返回 false。
2 <= s.length <= 100。
s 由小写英文字母组成。
输入: s = "adcb"。
输出: true。
解释:
在下标 i = 1 处拆分:
左子字符串 = s[0..1] = "ad",得分 = 1 + 4 = 5。
右子字符串 = s[2..3] = "cb",得分 = 3 + 2 = 5。
两个子字符串的得分相等,因此输出为 true。
题目来自力扣3707。
你想让我根据给定的Go语言代码和“相等子字符串分数”的题目描述,详细拆解代码的执行过程,并分析其时间复杂度和空间复杂度。
我们以输入字符串 s = "adcb" 为例,一步步拆解 scoreBalance 函数的执行逻辑:
b & 31 是一个技巧——小写字母的ASCII码二进制最后5位恰好对应1-26(如a的ASCII是97,二进制01100001,&31后是00000001即1;d的ASCII是100,二进制01100100,&31后是00000100即4)。total = 10。left,遍历每个字符时将其序号加入left,然后检查 left * 2 == total(即左侧分值等于右侧分值)。left*2 也等于total(此时left=total),但left*2=total 等价于total=0,而字符串长度≥2且字符序号≥1,因此最后一个字符必然不满足,无需额外限制遍历范围。left = 0;true;s = "adcb",调用scoreBalance函数,得到返回值true,最后打印结果。n成正比。n,第一次遍历耗时O(n),第二次遍历最坏情况下(无满足条件的切点)耗时O(n),总时间复杂度为O(n) + O(n) = O(n)。n ≤ 100,实际执行效率极高,但从算法角度,时间复杂度为线性时间复杂度O(n)。total、left两个整型变量,以及遍历过程中的临时变量(如b),这些变量的空间占用与字符串长度无关,属于常数级。b & 31的技巧,等价于将小写字母转换为1-26的序号;.
package main
import (
"fmt"
)
func scoreBalance(s string)bool {
total := 0
for _, b := range s {
total += int(b & 31)
}
left := 0
for _, b := range s { // 字母位置是正数,可以遍历到 s 末尾(末尾一定不满足要求)
left += int(b & 31)
if left*2 == total {
returntrue
}
}
returnfalse
}
func main() {
s := "adcb"
result := scoreBalance(s)
fmt.Println(result)
}

.
# -*-coding:utf-8-*-
def score_balance(s: str) -> bool:
total = 0
for ch in s:
total += ord(ch) & 31
left = 0
for ch in s:
left += ord(ch) & 31
if left * 2 == total:
return True
return False
def main():
s = "adcb"
result = score_balance(s)
print(result)
if __name__ == "__main__":
main()
.
#include <iostream>
#include <string>
bool scoreBalance(const std::string& s) {
int total = 0;
for (char b : s) {
total += static_cast<int>(b & 31);
}
int left = 0;
for (char b : s) {
left += static_cast<int>(b & 31);
if (left * 2 == total) {
returntrue;
}
}
returnfalse;
}
int main() {
std::string s = "adcb";
bool result = scoreBalance(s);
std::cout << std::boolalpha << result << std::endl;
return0;
}
·
我们相信人工智能为普通人提供了一种“增强工具”,并致力于分享全方位的AI知识。在这里,您可以找到最新的AI科普文章、工具评测、提升效率的秘籍以及行业洞察。 欢迎关注“福大大架构师每日一题”,发消息可获得面试资料,让AI助力您的未来发展。
·