- Initialize
powerandlento 1 since a single character has power 1. - Iterate through the string starting from index 1.
- If the current character matches the previous character, increment the current length.
- If the characters don't match, reset the length to 1.
- Update the maximum power after each iteration.
// Look backward
fun maxPower(s: String): Int {
var power = 1
var len = 1
for (i in 1 until s.length) {
if (s[i - 1] == s[i]) {
len++
} else {
len = 1
}
power = maxOf(power, len)
}
return power
}
// Equivalent, look ahead
for maxPower(s: String): Int {
var power = 1
var len = 1
for (i in 0 until s.length - 1) {
if (s[i] == s[i + 1]) {
len++
} else {
len = 1
}
power = maxOf(power, len)
}
return power
}
// Or equivalent: we track the previous character to check if it's consecutive.
fun maxPower(s: String): Int {
var power = 0
var len = 0
var previous = ' '
for (i in 0 until s.length) {
if (s[i] == previous) {
len++
} else {
len = 1
previous = s[i]
}
power = maxOf(power, len)
}
return power
}Use a while loop to group consecutive identical characters, measuring the length of each group and updating the maximum found. 靈神模板
fun maxPower(s: String): Int {
var power = 0
var i = 0
while (i < s.length) {
val current = s[i]
val start = i
i++
while (i < s.length && s[i] == current) {
i++
}
// `i` will be the next index of the current group. (the start of the next group)
power = maxOf(power, i - start)
}
return power
}
// Or equivalent: We move `i` only when we have the same "next" character. `i` will stop at the end of the current group.
fun maxPower(s: String): Int {
var power = 0
var i = 0
while (i < s.length) {
val current = s[i]
val start = i
while (i + 1 < s.length && s[i + 1] == current) {
i++
}
power = maxOf(power, i - start + 1)
i++
}
return power
}Or the same idea but to use a sliding window to expand over runs of identical characters.
a, b, b, b, b, c
i // Start of the current group.
j --------> j // Expand the window until the characters are different.
i // Next group starts at index i.fun maxPower(s: String): Int {
var power = 0
var i = 0
while (i < s.length) {
var j = i
while (j < s.length && s[i] == s[j]) j++
// `j` will be the next index of the current group. (the start of the next group)
power = maxOf(power, j - i)
// Jump `i` to the new starting position of "next group".
i = j
}
return power
}All implementations are O(n) time and O(1) space.