|
…
|
||
|---|---|---|
| .. | ||
| README.md | ||
| README_EN.md | ||
| Solution.cpp | ||
| Solution.cs | ||
| Solution.go | ||
| Solution.java | ||
| Solution.php | ||
| Solution.py | ||
| Solution.rs | ||
| Solution.ts | ||
README_EN.md
| comments | difficulty | edit_url | rating | source | tags | |
|---|---|---|---|---|---|---|
| true | Easy | https://github.com/doocs/leetcode/edit/main/solution/3100-3199/3110.Score%20of%20a%20String/README_EN.md | 1152 | Biweekly Contest 128 Q1 |
|
3110. Score of a String
Description
You are given a string s. The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters.
Return the score of s.
Example 1:
Input: s = "hello"
Output: 13
Explanation:
The ASCII values of the characters in s are: 'h' = 104, 'e' = 101, 'l' = 108, 'o' = 111. So, the score of s would be |104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13.
Example 2:
Input: s = "zaz"
Output: 50
Explanation:
The ASCII values of the characters in s are: 'z' = 122, 'a' = 97. So, the score of s would be |122 - 97| + |97 - 122| = 25 + 25 = 50.
Constraints:
2 <= s.length <= 100sconsists only of lowercase English letters.
Solutions
Solution 1: Simulation
We directly traverse the string s, calculating the sum of the absolute differences of the ASCII codes of adjacent characters.
The time complexity is O(n), where n is the length of the string s. The space complexity is O(1).
Python3
class Solution:
def scoreOfString(self, s: str) -> int:
return sum(abs(a - b) for a, b in pairwise(map(ord, s)))
Java
class Solution {
public int scoreOfString(String s) {
int ans = 0;
for (int i = 1; i < s.length(); ++i) {
ans += Math.abs(s.charAt(i - 1) - s.charAt(i));
}
return ans;
}
}
C++
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;
}
};
Go
func scoreOfString(s string) (ans int) {
for i := 1; i < len(s); i++ {
ans += abs(int(s[i-1]) - int(s[i]))
}
return
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
TypeScript
function scoreOfString(s: string): number {
let ans = 0;
for (let i = 1; i < s.length; ++i) {
ans += Math.abs(s.charCodeAt(i) - s.charCodeAt(i - 1));
}
return ans;
}
Rust
impl Solution {
pub fn score_of_string(s: String) -> i32 {
s.as_bytes()
.windows(2)
.map(|w| (w[0] as i32 - w[1] as i32).abs())
.sum()
}
}
C#
public class Solution {
public int ScoreOfString(string s) {
int ans = 0;
for (int i = 1; i < s.Length; ++i) {
ans += Math.Abs(s[i] - s[i - 1]);
}
return ans;
}
}
PHP
class Solution {
/**
* @param String $s
* @return Integer
*/
function scoreOfString($s) {
$ans = 0;
$n = strlen($s);
for ($i = 1; $i < $n; ++$i) {
$ans += abs(ord($s[$i]) - ord($s[$i - 1]));
}
return $ans;
}
}