HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Longest running string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
longestrunningstring

Problem

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 = substr.length()) {
                substr = tempSubstr;

            }
            i += 1;
        }
        System.out.println(substr);
        return substr.length();
    }

}

Solution

You should keep 4 variables:

  • The start index of the longest run



  • The end index (or length) of the longest run



  • The start index of the current run



  • The iterating index



For performance, you'd likely also store the char of the current run in a variable.

When done iterating, return substring of longest run.

Context

StackExchange Code Review Q#109172, answer score: 10

Revisions (0)

No revisions yet.