LeetCode 2223: Sum of Scores of Built Strings
Problem Description
Explanation
To solve this problem, we can iterate through the string from left to right, keeping track of the longest common prefix between the current substring and the original string. We can maintain this information using a prefix array. The score of each substring is the length of the longest common prefix.
Algorithm
- Initialize a variable
n
to store the length of the input strings
. - Initialize a variable
result
to store the total sum of scores. - Initialize an array
prefix
of sizen
to store the prefix scores of each substring. - Iterate from index 1 to
n
in the input strings
.- For each index
i
, calculate the longest common prefix betweens.substring(0, i+1)
ands
itself. - Update
prefix[i-1]
with the length of the longest common prefix.
- For each index
- Calculate the total sum of scores by adding all elements of the
prefix
array. - Return the total sum of scores as the result.
Time Complexity
The time complexity of this algorithm is O(n) where n is the length of the input string s
.
Space Complexity
The space complexity of this algorithm is O(n) for the prefix
array.
Solutions
class Solution {
public int sumOfScores(String s) {
int n = s.length();
int result = 0;
int[] prefix = new int[n];
for (int i = 1; i <= n; i++) {
prefix[i-1] = longestCommonPrefix(s.substring(0, i), s);
}
for (int p : prefix) {
result += p;
}
return result;
}
private int longestCommonPrefix(String s1, String s2) {
int i = 0;
while (i < s1.length() && i < s2.length() && s1.charAt(i) == s2.charAt(i)) {
i++;
}
return i;
}
}
Loading editor...