连续字符Java
文章发布较早,内容可能过时,阅读注意甄别。
# 题目
给你一个字符串 s ,字符串的「能量」定义为:只包含一种字符的最长非空子字符串的长度。
请你返回字符串 s 的 能量。
示例 1:
输入:s = "leetcode"
输出:2
解释:子字符串 "ee" 长度为 2 ,只包含字符 'e' 。
示例 2:
输入:s = "abbcccddddeeeeedcba"
输出:5
解释:子字符串 "eeeee" 长度为 5 ,只包含字符 'e' 。
提示:
- 1 <= s.length <= 500
- s 只包含小写英文字母。
# 思路
toCharArray
# 解法
class Solution {
public static int maxPower(String s) {
char[] chars = s.toCharArray();
int count = 1, max = 0;
for (int i = 1; i < chars.length; i++) {
count += chars[i] == chars[i - 1] ? 1 : -count + 1;
max = Math.max(max, count);
}
return Math.max(max, count);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 总结
- 分析出几种情况,然后分别对各个情况实现


