Hi Everyone, This was the first attempt answer for the Leetcode problem on score of a string.
https://leetcode.com/problems/score-of-a-string
class Solution { public int scoreOfString(String s) { sum = 0; char[] ssize = s.toCharArray(); for (int i=0;i<ssize.length-1; i++){ sum = sum + abs(ssize(i).asciicode-ssize(i+1).asciicode) } return sum }
Issue | Description |
---|---|
sum not declared - |
sum is used without type declaration. |
Incorrect syntax: abs() - |
Java requires Math.abs() for absolute value. |
Incorrect character access: ssize(i) - |
Use ssize[i] , not parentheses. |
Non-existent property: .asciicode |
Characters in Java already act as ASCII values when cast to int . |
Missing semicolons and braces | Several semicolons and } missing. |
Overall formatting and structure | Needs improvement for clarity and compilation. |
Learning from the code:
1. Declare the variables.
2. For each Math method, use Math.<method>
3. Array access using [].
4. asciiCode. each character has a ascii value, which can be used while converting to int.
5. colons are missing
Corrected code for this
class Solution { public int scoreOfString(String s) { int sum = 0; char[] ssize = s.toCharArray(); for (int i = 0; i < ssize.length - 1; i++) { sum += Math.abs(ssize[i] - ssize[i + 1]); } return sum; } }
No comments:
Post a Comment