File tree Expand file tree Collapse file tree 2 files changed +66
-0
lines changed
main/java/by/andd3dfx/string
test/java/by/andd3dfx/string Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments