3110. Score of a String
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\nThe given C++ function scoreOfString calculates a specific score for a 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\nThe given C++ function scoreOfString calculates a specific score for a given string s. Here is a step-by-step description of the approach:\n\nFunction Signature:\n\nThe function scoreOfString takes a single argument, a string s, and returns an integer representing the score.\nInitialization:\n\nAn integer variable ans is initialized to 0. This variable will store the cumulative score as the function processes the string.\nIteration Through the String:\n\nA for loop iterates through the string s from the first character to the second-to-last character (i.e., i ranges from 0 to s.length()-2). The loop ensures that each character except the last one is considered for the scoring process.\nScore Calculation:\n\nWithin the loop, the absolute difference between the ASCII values of the current character s[i] and the next character s[i+1] is computed using the abs function.\nThis absolute difference is then added to the ans variable.\nReturn the Result:\n\nAfter the loop completes, the function returns the accumulated score stored in ans.\nExample Walkthrough\nLet\'s go through an example to illustrate how the function works:\n\nExample Input: "abcd"\n\nThe function initializes ans to 0.\nThe loop iterates over the string:\nFor i = 0, s[0] = \'a\' and s[1] = \'b\'. The absolute difference is abs(\'a\' - \'b\') = abs(97 - 98) = 1. ans is updated to 1.\nFor i = 1, s[1] = \'b\' and s[2] = \'c\'. The absolute difference is abs(\'b\' - \'c\') = abs(98 - 99) = 1. ans is updated to 2.\nFor i = 2, s[2] = \'c\' and s[3] = \'d\'. The absolute difference is abs(\'c\' - \'d\') = abs(99 - 100) = 1. ans is updated to 3.\nThe loop ends since there are no more characters to process.\nThe function returns the final score 3.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n-  the overall time complexity of the scoreOfString function is \n\uD835\uDC42(\uD835\uDC5B), where n is the length of the input string s. This indicates that the function runs in linear time relative to the size of the input.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code : C++\n```\nclass Solution {\npublic:\n    int scoreOfString(string s) {\n        int ans = 0;\n        for(int i=0;i<s.length()-1;i++)\n        {\n            ans+=abs(s[i]-s[i+1]);\n        }\n        return ans;\n    }\n};\n```\n# Code : Python\n```\nclass Solution:\n    def scoreOfString(self, s: str) -> int:\n        ans = 0\n        for i in range(len(s)-1):\n            ans+=abs(ord(s[i])-ord(s[i+1]))\n        return ans\n```\n
['C++', 'Python3']