「每日LeetCode」2021年12月1日

本文最后更新于:2023年3月19日 晚上

  1. 连续字符

1446. 连续字符

给你一个字符串 s ,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。
请你返回字符串的能量。

示例 1:
输入:s = “leetcode” 输出:2 解释:子字符串 “ee” 长度为 2 ,只包含字符 ‘e’ 。
示例 2:
输入:s = “abbcccddddeeeeedcba” 输出:5 解释:子字符串 “eeeee” 长度为 5 ,只包含字符 ‘e’ 。
示例 3:
输入:s = “triplepillooooow” 输出:5
示例 4:
输入:s = “hooraaaaaaaaaaay” 输出:11
示例 5:
输入:s = “tourist” 输出:1

提示:

  • 1 <= s.length <= 500
  • s 只包含小写英文字母。

思路

按题意遍历计数更新最大值即可。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @param {string} s
* @return {number}
*/
var maxPower = function (s) {
if (s.length <= 1) return s.length;
let max = 0,
prev = s[0],
count = 0;
for (const num of s) {
if (prev === num) count++;
else {
max = Math.max(max, count);
count = 1;
prev = num;
}
}
return Math.max(max, count);
};