Differences of adjacent characters' ASCII values. || Beats 99% users with java & c++ || typescript
Approach\nDifferences of adjacent characters\' ASCII values.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Explanation\n1. Initializ
# Approach\nDifferences of adjacent characters\' ASCII values.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Explanation\n1. **Initialize totalScore:** Start with a variable totalScore set to 0. This will accumulate the sum of the absolute differences.\n\n1. **Loop through the string:** Use a for loop to iterate from the first character to the second last character of the string (i < s.length() - 1).\n\n1. **Compute absolute difference:** For each character at position i, compute the absolute difference between the ASCII values of the character at position i (s.charAt(i)) and the next character (s.charAt(i + 1)). Use Math.abs to get the absolute difference.\n\n1. **Accumulate the score:** Add this difference to totalScore.\nReturn the result: After the loop completes, return the totalScore.\n\n\n---\n\n```java []\nclass Solution {\n    public int scoreOfString(String s) {\n        int totalScore = 0;\n        for (int i = 0; i < s.length() - 1; i++) {\n            totalScore += Math.abs(s.charAt(i) - s.charAt(i + 1));\n        }\n        return totalScore;\n    }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n    int scoreOfString(std::string s) {\n        int totalScore = 0;\n        for (int i = 0; i < s.length() - 1; i++) {\n            totalScore += std::abs(s[i] - s[i + 1]);\n        }\n        return totalScore;\n    }\n};\n```\n```python3 []\nclass Solution:\n    def scoreOfString(self, s: str) -> int:\n        total_score = 0\n        for i in range(len(s) - 1):\n            total_score += abs(ord(s[i]) - ord(s[i + 1]))\n        return total_score\n\n```\n```Typescript []\nfunction scoreOfString(s: string): number {\n    let totalScore = 0;\n    for (let i = 0; i < s.length - 1; i++) {\n        totalScore += Math.abs(s.charCodeAt(i) - s.charCodeAt(i + 1));\n    }\n    return totalScore;\n}\n```\n
['String', 'C++', 'Java', 'TypeScript', 'Python3']