【拒绝算法PUA】Leetcode 3110. 字符串的分数

系列文章目录

【拒绝算法PUA】0x00-位运算
【拒绝算法PUA】0x01- 区间比较技巧
【拒绝算法PUA】0x02- 区间合并技巧
【拒绝算法PUA】0x03 - LeetCode 排序类型刷题
【拒绝算法PUA】LeetCode每日一题系列刷题汇总-2025年持续刷新中

C++刷题技巧总结:
[温习C/C++]0x04 刷题基础编码技巧



LeetCode 3110. 字符串的分数

难度:简单

链接

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年持续刷新中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值