Given a string
s
, the power of the string is the maximum length of a non-empty substring that contains only one unique character.Find the power of the string.
Example 1:
Input: s = "abbcccddddeeeeedcba"
Output: 5
Approach
Java
public class ConsecutiveCharacters {public static void main(String[] args) {String str = "abbcccddddeeeeedcba";System.out.println(maxPower(str));}static int maxPower(String s) {int n = s.length();int i = 0;int max1 = 0;while (i < n) {int cnt = 1;while (i < n - 1 && s.charAt(i) == s.charAt(i + 1)) {cnt++;i++;}i++;max1 = Math.max(cnt, max1);}return max1;}}
C++
#include <bits/stdc++.h>using namespace std;int maxPower(string s){int n = s.size();int i = 0;int max1 = 0;while (i < n){int cnt = 1;while (i < n - 1 && s[i] == s[i + 1]){cnt++;i++;}i++;max1 = max(cnt, max1);}return max1;}int main(){string str = "abbcccddddeeeeedcba";cout << maxPower(str);return 0;}
No comments:
Post a Comment