题目描述
给你一个字符串 s ,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。
请你返回字符串的能量。
输入:s = “abbcccddddeeeeedcba”
输出:5
解释:子字符串 “eeeee” 长度为 5 ,只包含字符 ‘e’ 。
思路
一次遍历,不断更新答案即可。
class Solution {
public int maxPower(String s) {
char[] chars = s.toCharArray();
int res = 1, c = 1;
for (int i = 0; i < chars.length - 1; i++) {
if (chars[i] == chars[i + 1]) {
c++;
res = Math.max(res, c);
} else {
c = 1;
}
}
return res;
}
}