Consecutive Characters LeetCode solution in Java

1
class Solution {
2
public int maxPower(String s) {
3
// O(n), assuming the access to every char is O(1)
4
// iterate through characters
5
// if char(n) == char(n+1) counter++
6
// if counter > max, max = counter
7
// else counter = 1 // 1 is init value because otherwise the compared char itself is not counted
8

9
int maxConsecutive =
10
1; // 1 is init value because otherwise the compared char itself is not counted
11
int counterConsecutive = 1;
12
for (int i = 0; i < s.length() - 1; i++) {
13
if (s.charAt(i) == s.charAt(i + 1)) {
14
counterConsecutive++;
15
maxConsecutive = Math.max(counterConsecutive, maxConsecutive);
16
} else {
17
counterConsecutive = 1;
18
}
19
}
20

21
return maxConsecutive;
22
}
23
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0