题目

Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.

Return the power of the string.

Example 1:

  1. Input: s = "leetcode"
  2. Output: 2
  3. Explanation: The substring "ee" is of length 2 with the character 'e' only.

Example 2:

  1. Input: s = "abbcccddddeeeeedcba"
  2. Output: 5
  3. Explanation: The substring "eeeee" is of length 5 with the character 'e' only.

Example 3:

  1. Input: s = "triplepillooooow"
  2. Output: 5

Example 4:

  1. Input: s = "hooraaaaaaaaaaay"
  2. Output: 11

Example 5:

  1. Input: s = "tourist"
  2. Output: 1

Constraints:

  • 1 <= s.length <= 500
  • s contains only lowercase English letters.

题意

计算给定字符串中最长连续相同字符的长度。

思路

一次遍历。


代码实现

Java

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