系列文章目录
【拒绝算法PUA】0x00-位运算
【拒绝算法PUA】0x01- 区间比较技巧
【拒绝算法PUA】0x02- 区间合并技巧
【拒绝算法PUA】0x03 - LeetCode 排序类型刷题
【拒绝算法PUA】LeetCode每日一题系列刷题汇总-2025年持续刷新中
C++刷题技巧总结:
[温习C/C++]0x04 刷题基础编码技巧
LeetCode 3110. 字符串的分数
难度:简单
链接
题目
给你一个字符串 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 只包含小写英文字母。
解题方法1
#include <iostream>
using namespace std;
class Solution {
public:
int scoreOfString(string s) {
int res = 0;
if (s.empty()) {
return res;
}
char pre = s[0];
int index = 1;
while (index < s.size()) {
char curr = s[index];
res += abs(pre - curr);
pre = curr;
index++;
}
return res;
}
};
int main(int argc, char **argv) {
string s = "hello";
Solution obj;
int ret = obj.scoreOfString(s);
cout << ret << endl;
return 0;
}
- 输出
13
关注我,跟我一起每日一题!
【拒绝算法PUA】LeetCode每日一题系列刷题汇总-2025年持续刷新中