I came across this problem in a career cup. Below I have the questions and the Java solution. I was wondering if anyone could scrutinize my code and tell me if there are any improvements, or better coding practices that I should know, as I am working on being able to produce proficient code.
Problem statement:
Write a program to accept a nonempty string of alphanumeric characters. Define a
run
as a consecutive sequence of a single character. For example,aaaa
is a run of length \$4\$. The program will print the longest run in the given string. If there is no single longest run, then you may print any of those runs whose length is at least as long as all other runs in the string.Example input: a Example output: a Example input: aab Example output: aa Example input: abbbbbcc Example output: bbbbb Example input: aabbccdd Example output: aa
Solution:
public class StringRunCount {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(maxRun("aaabbbbbbbbcccccc"));
}
public static int maxRun(String testString) {
int len = testString.length();
String substr = "";
for (int i = 0; i < len;) {
char current = testString.charAt(i);
String tempSubstr = "" + current;
while ((i + 1) < len && (current == testString.charAt(i + 1))) {
tempSubstr = tempSubstr + testString.charAt(++i);
}
if (tempSubstr.length() >= substr.length()) {
substr = tempSubstr;
}
i += 1;
}
System.out.println(substr);
return substr.length();
}
}
String = String + String
in a loop. – Andreas Oct 29 at 20:28Strings
in loops usingStringBuffer
or something similar instead of string addition (which is very inefficient). 2) if you know thatcurrent == testString.charAt(...)
, why are you extracting the char again to concatenate to yourtempSubStr
? Usecurrent
instead:tempSubStr += current;
– brimborium Oct 29 at 20:34