【LetMeFly】3110.字符串的分数:模拟(注意一个小细节)
力扣题目链接:https://leetcode.cn/problems/score-of-a-string/
给你一个字符串 s
。一个字符串的 分数 定义为相邻字符 ASCII 码差值绝对值的和。
请你返回 s
的 分数 。
示例 1:
**输入:**s = "hello"
**输出:**13
解释:
s
中字符的 ASCII 码分别为:'h' = 104
,'e' = 101
,'l' = 108
,'o' = 111
。所以 s
的分数为 |104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13
。
示例 2:
**输入:**s = "zaz"
**输出:**50
解释:
s
中字符的 ASCII 码分别为:'z' = 122
,'a' = 97
。所以 s
的分数为 |122 - 97| + |97 - 122| = 25 + 25 = 50
。
提示:
2 <= s.length <= 100
s
只包含小写英文字母。
解题方法:模拟
直接从第二个字符开始遍历字符串,将这个字符减去前一个字符的绝对值累加到答案中,最终返回即可。
注意:请谨慎使用8比特数减8比特数(如char - char或byte - byte),因为有的编程语言中8比特数相减不会类型提升转为int相减。
如下代码的运行结果为255和255:
go
package main
import "fmt"
func main() {
a := byte(1)
b := byte(2)
c := a - b
fmt.Println(c) // 255
d := int(c)
fmt.Println(d) // 255
}
- 时间复杂度 O ( l e n ( s ) ) O(len(s)) O(len(s))
- 空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C++
cpp
/*
* @Author: LetMeFly
* @Date: 2025-03-15 10:26:54
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-03-15 10:27:59
*/
#ifdef _WIN32
#include "_[1,2]toVector.h"
#endif
class Solution {
public:
int scoreOfString(string s) {
int ans = 0;
for (int i = 1; i < s.size(); i++) {
ans += abs(s[i] - s[i - 1]);
}
return ans;
}
};
Python
python
'''
Author: LetMeFly
Date: 2025-03-15 10:28:26
LastEditors: LetMeFly.xyz
LastEditTime: 2025-03-15 10:28:50
'''
class Solution:
def scoreOfString(self, s: str) -> int:
return sum(abs(ord(s[i]) - ord(s[i - 1])) for i in range(1, len(s)))
Java
java
/*
* @Author: LetMeFly
* @Date: 2025-03-15 10:36:15
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-03-15 10:36:23
*/
class Solution {
public int scoreOfString(String s) {
int ans = 0;
for (int i = 1; i < s.length(); i++) {
ans += Math.abs(s.charAt(i) - s.charAt(i - 1));
}
return ans;
}
}
Go
go
/*
* @Author: LetMeFly
* @Date: 2025-03-15 10:29:29
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-03-15 10:32:20
*/
package main
func abs3110(a int) int {
if a < 0 {
return -a
}
return a
}
func scoreOfString(s string) (ans int) {
for i := 1; i < len(s); i++ {
ans += abs3110(int(s[i]) - int(s[i - 1]))
}
return
}
同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~
千篇源码题解已开源