【題目】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】
class Solution {
public int maxPower(String s) {
if (s.length() == 0) return 0;
if (s.length() == 1) return 1;
char cur = s.charAt(0);
int max = 0;
int count = 0;
for(char c : s.toCharArray()){
if(cur == c){
count++;
}else{
cur = c;
max = Math.max(max, count);
count = 1;
}
}
return Math.max(max, count);
}
}
class Solution {
public int maxPower(String s) {
int ans = 1;
int count = 1;
for(int i = 1; i < s.length(); i++){
if(s.charAt(i) == s.charAt(i-1)){
count++;
ans = Math.max(count, ans);
}
else{
count = 1;
}
}
return ans;
}
}