字串評分程式
**字串的評分**是一個用於根據字串中相鄰字元的ASCII值之間的絕對差之和來計算評分的概念。
問題陳述
給定一個字串 s,計算字串的評分。評分定義為相鄰字元的ASCII值之間的絕對差之和。
示例場景 1
Input: s="abc"
Output: 2
s 中字元的ASCII值為 'a' = 97,'b' = 98,'c' = 99。因此,s 的評分 = |97-98|+|98-99|= 1+1 = 2 。
示例場景 2
Input: s="zaz"
Output: 50
s 中字元的ASCII值為 'z' = 122,'a' = 97。因此,s 的評分 = |122-97|+|97-122|=25+25=50。
示例場景 3
Input: s="nice"
Output: 13
s 中字元的ASCII值為 'n' = 110,'i' = 105,'c'=99,'e'=101。因此,s 的評分 = |110-105|+|105-99|+|99-101|+=5+6+2=13。
時間複雜度
計算字串評分的時間複雜度為 O(n),其中 n 為字串的長度。
為了用各種程式語言解決此問題,請使用以下方法。
- 使用迭代方法
- 使用列表推導式
使用迭代方法
迭代方法透過新增相鄰字元的ASCII值之間的絕對差來計算字串的評分。
示例
在此程式中,我們將評分初始化為 0,並從第二個字元迭代到字串末尾。然後,我們計算每個字元的ASCII值與其前一個字元的ASCII值之間的絕對差,並將這些差值新增到評分中。
#include <iostream> #include <cmath> using namespace std; int scoreOfString(string s) { int score = 0; for (int i = 1; i < s.length(); ++i) { score += abs(s[i] - s[i - 1]); } return score; } int main() { string s = "nice"; cout << "Score of the string = " << scoreOfString(s) << endl; return 0; }
輸出
Score of the string = 13
public class ScoreOfString { public static int scoreOfString(String s) { int score = 0; for (int i = 1; i < s.length(); i++) { score += Math.abs(s.charAt(i) - s.charAt(i - 1)); } return score; } public static void main(String[] args) { String s = "nice"; System.out.println("Score of the string = " + scoreOfString(s)); } }
輸出
Score of the string = 13
def score_of_string(s): score = 0 for i in range(1, len(s)): score += abs(ord(s[i]) - ord(s[i - 1])) return score s = "nice" print(f"Score of the string = {score_of_string(s)}")
輸出
Score of the string = 13
使用列表推導式
使用列表推導式為字串評分涉及建立一種簡潔有效的方法。此方法利用Python的列表推導式來遍歷字串並在單行程式碼中計算這些差異。
示例
此程式首先將相鄰字元的ASCII值之間的絕對差儲存在一個向量中,然後將這些差值加起來以獲得最終評分,從而計算字串的評分。main函式透過計算並列印字串“nice”的評分來演示這一點。
示例
#include <iostream> #include <cmath> #include <vector> using namespace std; int scoreOfString(string s) { vector<int> diffs; for (int i = 1; i < s.length(); ++i) { diffs.push_back(abs(s[i] - s[i - 1])); } int score = 0; for (int diff : diffs) { score += diff; } return score; } int main() { string s = "nice"; cout << "Score of the string = " << scoreOfString(s) << endl; return 0; }
輸出
Score of the string = 13
import java.util.stream.IntStream; public class ScoreOfString { public static int scoreOfString(String s) { return IntStream.range(1, s.length()) .map(i -> Math.abs(s.charAt(i) - s.charAt(i - 1))) .sum(); } public static void main(String[] args) { String s = "nice"; System.out.println("Score of the string = " + scoreOfString(s)); } }
輸出
Score of the string = 13
import math def scoreOfString(s): diffs = [] for i in range(1, len(s)): diffs.append(abs(ord(s[i]) - ord(s[i - 1]))) score = sum(diffs) return score s = "nice" print(f"Score of the string = {scoreOfString(s)}")
輸出
Score of the string = 13
廣告