序
本文次要记录一下leetcode之间断字符
题目
给你一个字符串 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 只蕴含小写英文字母。
起源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/consecutive-characters
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
题解
class Solution {
public int maxPower(String s) {
char[] chars = s.toCharArray();
int count = 1;
int result = 1;
for (int i = 1; i < chars.length; i++) {
count = chars[i] == chars[i - 1] ? count + 1 : 1;
result = Math.max(result, count);
}
return result;
}
}
小结
这里对字符数组进行遍历,从第二个字符开始,每次与前一个字符比拟,如果相等则递增count,如果不等则重置count为1,而后从新计算result
doc
- 间断字符
发表回复