Problem Statement
The power of the string is the maximum length of a non-empty substring that contains only one unique character.
Given a string s
, return the power of s
.
Constraints
1 ≤ s.length ≤ 500
s
consists of only lowercase English letters.
Examples
Example 1:
Input: s = "thejaat"
Output: 2
Explanation: The substring "aa" is of length 2 with character 'a' only.
Example 2:
Input: s = "aaabbbbccccc"
Output: 5
Explanation: The substring "ccccc" is of length 5 with the character 'c' only.
Different Approaches
1️⃣ Single Traversal Counting
Intuition:
Traverse the string, count consecutive occurrences of the same character, and keep updating the maximum count. Reset the counter whenever the character changes.
Approach:
- Initialize
count = 1
andmaxCount = 1
. - Loop from index 1 to end of string:
- If
s[i] == s[i-1]
, incrementcount
. - Else, reset
count = 1
. - Update
maxCount = max(maxCount, count)
- If
- Return
maxCount
Code:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxPower(string s) {
int maxCount = 1, count = 1;
for (int i = 1; i < s.size(); i++) {
if (s[i] == s[i-1]) {
count++;
} else {
count = 1;
}
maxCount = max(maxCount, count);
}
return maxCount;
}
};
int main() {
string s = "abbcccddddeeeeedcba";
Solution sol;
cout << "Power of the string is " << sol.maxPower(s) << endl;
return 0;
}
Complexity Analysis:
- Time Complexity:
O(n)
, wheren
is the length of the string. - Space Complexity:
O(1)
, only a few variables are used.
2️⃣ Using Two-Pointer Technique
Intuition:
Use two pointers to keep track of the start and of consecutive characters. Whenever a different character is found, calculate the length of the current block and update the maximum.
Approach:
- Initialize
i = 0
andmaxPower = 0
. - Loop
j
from 0 to end of string:- If
s[j] != s[i]
, movei = j
to start of new block. - Update
maxPower = max(maxPower, j - i + 1)
.
- If
- Return
maxPower
.
Code:
class Solution {
public:
int maxPower(string s) {
int maxCount = 0;
int i = 0;
int j = 0;
while(j < s.size()) {
if (s[i] != s[j]) {
i = j;
} else {
maxCount = max(maxCount, j - i + 1);
}
j++;
}
return maxCount;
}
};
Complexity Analysis:
- Time Complexity:
O(n)
, single pass over the string. - Space Complexity:
O(1)
, no extra variables used.