Java Easy to Understand Solution with Explanation || 100% beats
Intuition\n> Iterate through the string and remember the last ASCII value.\n\n# Approach\n\n\n\n1. Initialization:\n    - int ans = 0;: This initializes the var
# Intuition\n> Iterate through the string and remember the last ASCII value.\n\n# Approach\n\n\n\n1. **Initialization**:\n    - `int ans = 0;`: This initializes the variable `ans` to 0, which will hold the final score.\n    - `int size = s.length();`: This stores the length of the input string `s`.\n    - `int last = s.charAt(0);`: This initializes the `last` variable with the ASCII value of the first character in the string `s`.\n\n2. **Loop through the string**:\n    - `for (int i = 1; i < size; i++)`: This loop starts from the second character (`i = 1`) and iterates through the rest of the string.\n    - `ans += Math.abs(s.charAt(i) - last);`: For each character in the string (starting from the second character), the absolute difference between the ASCII values of the current character and the `last` character is calculated and added to `ans`.\n    - `last = s.charAt(i);`: The `last` variable is then updated to the current character for the next iteration.\n\n3. **Return the result**:\n    - `return ans;`: After the loop completes, the total score `ans` is returned.\n\n### Example\n\nConsider the input string `s = "abc"`:\n\n1. Initial values:\n    - `ans = 0`\n    - `size = 3`\n    - `last = \'a\'` (ASCII value 97)\n\n2. First iteration (`i = 1`):\n    - Current character: `s.charAt(1) = \'b\'` (ASCII value 98)\n    - `ans += Math.abs(98 - 97) = 1`\n    - Update `last = \'b\'`\n\n3. Second iteration (`i = 2`):\n    - Current character: `s.charAt(2) = \'c\'` (ASCII value 99)\n    - `ans += Math.abs(99 - 98) = 1`\n    - Update `last = \'c\'`\n\n4. Final value:\n    - `ans = 1 + 1 = 2`\n\nSo, the method would return `2` for the input string `"abc"`.\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public int scoreOfString(String s) {\n        int ans = 0;\n        int size = s.length();\n        int last = s.charAt(0);\n\n        for (int i = 1; i < size; i++) {\n            ans += Math.abs(s.charAt(i) - last);\n            last = s.charAt(i);\n        }\n\n        return ans;\n    }\n}\n```\n\n![image.png](https://assets.leetcode.com/users/images/73d4f4c6-43ca-4254-ab3e-7e88f44fbf0f_1717241760.3902442.png)\n
['String', 'Java']