题目

类型:String

image.png

解题思路

1、初始化当前字符连续出现次数 cnt 为 1。
2、从 s[1] 开始,向后遍历字符串,如果s[i]=s[i−1],则将 cnt 加一,否则将 cnt 重置为 1。
3、维护上述过程中 cnt 的最大值,即为答案。

代码

  1. class Solution {
  2. public int maxPower(String s) {
  3. int ans = 1, cnt = 1;
  4. for (int i = 1; i < s.length(); ++i) {
  5. if (s.charAt(i) == s.charAt(i - 1)) {
  6. ++cnt;
  7. ans = Math.max(ans, cnt);
  8. } else {
  9. cnt = 1;
  10. }
  11. }
  12. return ans;
  13. }
  14. }