LeetCode 3110.字符串的分数:模拟(注意一个小细节)

【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和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

千篇源码题解已开源

相关推荐
EkihzniY6 分钟前
OCR 发票识别与验真接口:助力电子化发票新时代
算法
一支鱼14 分钟前
leetcode-5-最长回文子串
算法·leetcode·typescript
茉莉玫瑰花茶1 小时前
算法 --- 分治(快排)
算法
闪电麦坤952 小时前
数据结构:哈希(Hashing)
数据结构·算法·哈希算法
l1t2 小时前
利用美团longcat.ai编写的C语言支持指定压缩算法通用ZIP压缩程序
c语言·开发语言·人工智能·算法·zip·压缩
hansang_IR3 小时前
【线性代数基础 | 那忘算9】基尔霍夫(拉普拉斯)矩阵 & 矩阵—树定理证明 [详细推导]
c++·笔记·线性代数·算法·矩阵·矩阵树定理·基尔霍夫矩阵
lingchen19063 小时前
MATLAB矩阵及其运算(三)矩阵的创建
算法·matlab·矩阵
野犬寒鸦3 小时前
力扣hot100:矩阵置零(73)(原地算法)
java·数据结构·后端·算法
Dream it possible!5 小时前
LeetCode 面试经典 150_矩阵_有效的数独(34_36_C++_中等)(额外数组)
leetcode·面试·矩阵
CoovallyAIHub5 小时前
4亿数据训练,零样本能力惊人:CLIP模型全解读
深度学习·算法·计算机视觉