1446. Consecutive Characters
Given a string s
, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.
Example 1:
Input: s = "leetcode" Output: 2 Explanation: The substring "ee" is of length 2 with the character 'e' only.
Example 2:
Input: s = "abbcccddddeeeeedcba" Output: 5 Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
Example 3:
Input: s = "triplepillooooow" Output: 5
Example 4:
Input: s = "hooraaaaaaaaaaay" Output: 11
Example 5:
Input: s = "tourist" Output: 1
class Solution { public int maxPower(String s) { if(s == null) return 0; if(s.length() <= 1) return s.length(); int res = 1; char[] ch = s.toCharArray(); int cursum = 1; for(int i = 1; i < ch.length; i++){ if(ch[i] != ch[i-1]){ cursum = 1; } else{ cursum++; res = Math.max(res, cursum); } } return res; } }
题意是找最长连续相等字符。从i=1开始和左边比较,如果不相等就从1重新开始,否则就cursum++。
class Solution { public int maxPower(String s) { int left = 0, n = s.length(), res = 0; char[] ch = s.toCharArray(); for(int right = 0; right < n; right++) { if(ch[right] != ch[left]) { while(left < right) left++; } res = Math.max(res, right - left + 1); } return res; } }
用sliding window,如果两个不相同就把left移动到right的位置