Skip to content

Commit a2a8ba3

Browse files
committed
Add solution of ConsecutiveCharacters task
1 parent 3bcfea7 commit a2a8ba3

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package by.andd3dfx.string;
2+
3+
/**
4+
* <pre>
5+
* <a href="https://leetcode.com/problems/consecutive-characters/">Task description</a>
6+
*
7+
* The power of the string is the maximum length of a non-empty substring that contains only one unique character.
8+
*
9+
* Given a string s, return the power of s.
10+
*
11+
* Example 1:
12+
* Input: s = "leetcode"
13+
* Output: 2
14+
* Explanation: The substring "ee" is of length 2 with the character 'e' only.
15+
*
16+
* Example 2:
17+
* Input: s = "abbcccddddeeeeedcba"
18+
* Output: 5
19+
* Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
20+
* </pre>
21+
*/
22+
public class ConsecutiveCharacters {
23+
24+
public static int maxPower(String s) {
25+
var n = s.length();
26+
var chars = s.toCharArray();
27+
28+
var left = 0;
29+
var right = 0;
30+
var max = 1;
31+
var curr = 1;
32+
while (right < n - 1) {
33+
right++;
34+
if (chars[right] == chars[left]) {
35+
curr++;
36+
} else {
37+
left = right;
38+
curr = 1;
39+
}
40+
41+
if (curr > max) {
42+
max = curr;
43+
}
44+
}
45+
46+
return max;
47+
}
48+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package by.andd3dfx.string;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.Test;
6+
7+
public class ConsecutiveCharactersTest {
8+
9+
@Test
10+
public void maxPower() {
11+
assertThat(ConsecutiveCharacters.maxPower("abcdef")).isEqualTo(1);
12+
assertThat(ConsecutiveCharacters.maxPower("ffffff")).isEqualTo(6);
13+
assertThat(ConsecutiveCharacters.maxPower("ggwpbbbbaac")).isEqualTo(4);
14+
15+
assertThat(ConsecutiveCharacters.maxPower("leetcode")).isEqualTo(2);
16+
assertThat(ConsecutiveCharacters.maxPower("abbcccddddeeeeedcba")).isEqualTo(5);
17+
}
18+
}

0 commit comments

Comments
 (0)