题目
类型:String
解题思路
1、初始化当前字符连续出现次数 cnt 为 1。
2、从 s[1] 开始,向后遍历字符串,如果s[i]=s[i−1],则将 cnt 加一,否则将 cnt 重置为 1。
3、维护上述过程中 cnt 的最大值,即为答案。
代码
class Solution {
public int maxPower(String s) {
int ans = 1, cnt = 1;
for (int i = 1; i < s.length(); ++i) {
if (s.charAt(i) == s.charAt(i - 1)) {
++cnt;
ans = Math.max(ans, cnt);
} else {
cnt = 1;
}
}
return ans;
}
}