Easy string vs adjacent_difference+accumulate vs 1-line recursion||0ms beats 100%
Intuition\n Describe your first thoughts on how to solve this problem. \nVery easy question!\n\nFor exercise, use C++ STL to make the 2nd approach; adjacent_dif
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nVery easy question!\n\nFor exercise, use C++ STL to make the 2nd approach; adjacent_difference, accumulate with lambda function\n\n3rd approach is 1-line recursion.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse a loop to iterate\n```\nfor(int i=1; i<n; i++)\n    ans+=abs(s[i]-s[i-1]);\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)\\to O(n)$$\n# Code||Python 1-liner| C, C++ 0ms beats 100%\n```C []\n#pragma GCC optimize("O3", "unroll-loops")\nstatic int scoreOfString(char* s) {\n    int ans=0;\n    for(register int i=1; s[i]!=\'\\0\'; i++)\n        ans+=abs(s[i]-s[i-1]);\n    return ans;\n}\n```\n```Python []\nclass Solution(object):\n    def scoreOfString(self, s):\n        return sum(abs(ord(s[i])-ord(s[i-1])) for i in range(1, len(s)))\n```\n```C++ []\nclass Solution {\npublic:\n    int scoreOfString(string& s) {\n        int n=s.size();\n        int ans=0;\n        for(int i=1; i<n; i++)\n            ans+=abs(s[i]-s[i-1]);\n        return ans;        \n    }\n};\n\n\nauto init = []() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    return \'c\';\n}();\n```\n\n# C++ using adjacent_difference+accumulate||0ms beats 100%\nFor testcase `s="hello"`, one has\n```\n[104,101,108,108,111] for s\n[104,-3,7,0,3] for s after adjacent_difference\n=> ans=|-3|+7+0+3=13\n```\n# C++ code\n```\nclass Solution {\npublic:\n    static int scoreOfString(string& s) {\n        adjacent_difference(s.begin(), s.end(), s.begin());\n        \n        //sum the absolute values of the differences, starting from the second element\n        return accumulate(s.begin()+1, s.end(), 0, [](int x, int y){\n            return x+abs(y);\n        });\n    }\n};\n\n```\n# Code 1-line recursion||C++ 0ms beats 100%\nFor 1-liner, add an extra parameter `int i=1`\n```C++ []\nclass Solution {\npublic:\n    int scoreOfString(string& s, int i=1) {\n        return (i==s.size())?0:abs(s[i]-s[i-1])+scoreOfString(s, i+1);\n    }\n};\n```\n```Python []\nclass Solution:\n    def scoreOfString(self, s: str, i: int=1) -> int:\n        return abs(ord(s[i])-ord(s[i-1]))+self.scoreOfString(s, i+1) if i!=len(s) else 0\n        \n```
['String', 'Recursion', 'C', 'Python', 'C++']