Skip to content

Character with Longest Consecutive Repetition in Java

The challenge

For a given string s find the character c (or C) with longest consecutive repetition and return:

Object[]{c, l};
Code language: Java (java)

where l (or L) is the length of the repetition. If there are two or more characters with the same l return the first in order of appearance.

For empty string return:

Object[]{"", }
Code language: Java (java)

Test cases

import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void exampleTests() { assertArrayEquals(new Object[]{"a", 4}, Solution.longestRepetition("aaaabb")); assertArrayEquals(new Object[]{"a", 4}, Solution.longestRepetition("bbbaaabaaaa")); assertArrayEquals(new Object[]{"u", 3}, Solution.longestRepetition("cbdeuuu900")); assertArrayEquals(new Object[]{"b", 5}, Solution.longestRepetition("abbbbb")); assertArrayEquals(new Object[]{"a", 2}, Solution.longestRepetition("aabb")); assertArrayEquals(new Object[]{"", }, Solution.longestRepetition("")); } }
Code language: Java (java)

The solution in java

Option 1:

public class Solution { public static Object[] longestRepetition(String s) { int len = s.length(); int count = ; if (len==) return new Object[]{"", }; char res = s.charAt(); for (int i=; i<len; i++) { int cur_count = 1; for (int j=i+1; j<len; j++) { if (s.charAt(i) != s.charAt(j)) break; cur_count++; } if (cur_count > count) { count = cur_count; res = s.charAt(i); } } return new Object[]{Character.toString(res), count}; } }
Code language: Java (java)

Option 2:

public class Solution { public static Object[] longestRepetition(String s) { char lastch = '\0'; Object ret[] = new Object[]{"", }; int n = , max = ; for (char c : s.toCharArray()) { n = lastch == c ? ++n : 1; if (n > max) { ret = new Object[]{""+c,n}; max = n; } lastch = c; } return ret; } }
Code language: Java (java)

See also  How to Make a Spiral in Java
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x