Leetcode 3110. Score of a String
You are given a string s
consisting only of characters a
, b
, and c
. The function scoreOfString(s: String) -> int
should return the score of the string, where the score is calculated as follows:
a
has a score of 1.b
has a score of 2.c
has a score of 3.For example, the score of the string "aaabbc"
is calculated as follows:
"aaa"
has a score of 1 * 3 = 3
"bb"
has a score of 2 * 2 = 4
"c"
has a score of 3 * 1 = 3
So, the total score of "aaabbc"
is 3 + 4 + 3 = 10
.s
?s
?a
, b
, and c
that we might need to handle?public class Solution {
public int scoreOfString(String s) {
if (s == null || s.length() == 0) return 0;
int totalScore = 0;
int currentScore = 0;
int currentCount = 0;
char prevChar = s.charAt(0);
for (char c : s.toCharArray()) {
if (c == prevChar) {
currentCount++;
} else {
// Calculate the score of the previous contiguous segment
totalScore += calculateSegmentScore(prevChar, currentCount);
// Reset for the new character segment
prevChar = c;
currentCount = 1;
}
}
// Handle the last segment
totalScore += calculateSegmentScore(prevChar, currentCount);
return totalScore;
}
private int calculateSegmentScore(char c, int count) {
int baseScore = 0;
switch (c) {
case 'a':
baseScore = 1;
break;
case 'b':
baseScore = 2;
break;
case 'c':
baseScore = 3;
break;
}
return baseScore * count;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.scoreOfString("aaabbc")); // Output: 10
System.out.println(sol.scoreOfString("abcabc")); // Output: 9
System.out.println(sol.scoreOfString("")); // Output: 0
System.out.println(sol.scoreOfString("aaa")); // Output: 3
}
}
totalScore
to 0
.currentScore
and currentCount
to 0
.prevChar
as the first character of the string s
.c
in the string s
.c
is the same as prevChar
, increment currentCount
.c
is different from prevChar
:
prevChar
and add it to totalScore
.prevChar
to the new character c
.currentCount
to 1
.totalScore
.calculateSegmentScore
to calculate the score for a segment of identical characters based on the character’s base score.n
is the length of the input string s
. We traverse the string once and perform constant-time operations.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?