LeetCode 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
只包含小写英文字母。
字符串
public static int maxPower(String s) {
if (s == null || s.length() == 0) return 0;
char[] chars = s.toCharArray();
char ch = chars[0];
int ans = 0;
int tmp = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] != ch) {
ans = Math.max(i - tmp, ans);
ch = chars[i];
tmp = i;
}
}
// 保证最后一段是长度最长的连续字符
ans = Math.max(chars.length - tmp, ans);
return ans;
}
public static void main(String[] args) {
String s = "leetcode";
int maxPower = MaxPower.maxPower(s);
System.out.println("MaxPower demo01 result : " + maxPower);
s = "abbcccddddeeeeedcba";
maxPower = MaxPower.maxPower(s);
System.out.println("MaxPower demo02 result : " + maxPower);
s = "triplepillooooow";
maxPower = MaxPower.maxPower(s);
System.out.println("MaxPower demo03 result : " + maxPower);
s = "hooraaaaaaaaaaay";
maxPower = MaxPower.maxPower(s);
System.out.println("MaxPower demo04 result : " + maxPower);
s = "tourist";
maxPower = MaxPower.maxPower(s);
System.out.println("MaxPower demo05 result : " + maxPower);
s = "touristtt";
maxPower = MaxPower.maxPower(s);
System.out.println("MaxPower demo06 result : " + maxPower);
}
测试结果
MaxPower demo01 result : 2
MaxPower demo02 result : 5
MaxPower demo03 result : 5
MaxPower demo04 result : 11
MaxPower demo05 result : 1
MaxPower demo06 result : 3