1446. Consecutive Characters
Explanation
To solve this problem, we can iterate through the input string and keep track of the current character and the count of consecutive occurrences of that character. We update the maximum power whenever we encounter a new character or the count of consecutive occurrences increases. Finally, we return the maximum power as the result.
- Initialize variables
maxPower
,currPower
,prevChar
to 1. - Iterate through the string starting from the second character.
- If the current character is the same as the previous character, increment
currPower
. - If the current character is different, update
maxPower
ifcurrPower
is greater and resetcurrPower
. - Return
maxPower
as the result.
Time Complexity: O(n) where n is the length of the input string s. Space Complexity: O(1)
class Solution {
public int maxPower(String s) {
int maxPower = 1;
int currPower = 1;
char prevChar = s.charAt(0);
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == prevChar) {
currPower++;
} else {
maxPower = Math.max(maxPower, currPower);
currPower = 1;
prevChar = s.charAt(i);
}
}
return Math.max(maxPower, currPower);
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.