LeetCode 2522: Partition String Into Substrings With Values at Most K
Problem Description
Explanation:
To solve this problem, we can iterate through the given string s
and maintain a running sum of the current substring value. If the value of the current substring exceeds k
, we increment the count of substrings and reset the running sum.
Algorithm:
- Initialize variables
count
to store the number of substrings,curValue
to store the current substring value, andi
as the index. - Iterate over the characters in the string
s
. - For each character:
- Calculate the integer value of the character.
- Update
curValue
by multiplying it by 10 and adding the integer value. - If
curValue
exceedsk
, incrementcount
and resetcurValue
to the integer value of the current character.
- Finally, check if
curValue
is greater than 0. If so, incrementcount
. - If there are no good partitions (i.e.,
count
is 0), return -1. Otherwise, returncount
.
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 is O(1) as we are using a constant amount of extra space.
:
Solutions
class Solution {
public int partitionString(String s, int k) {
int count = 0;
int curValue = 0;
for (int i = 0; i < s.length(); i++) {
int digitValue = s.charAt(i) - '0';
curValue = curValue * 10 + digitValue;
if (curValue > k) {
count++;
curValue = digitValue;
}
}
if (curValue > 0) {
count++;
}
return count == 0 ? -1 : count;
}
}
Loading editor...