Problem: Write a Java code to find the longest sequence of consecutive repetitive characters in a String. For example if a String is "aaaabbbbcccchhhhiiiiibbbbbbbbbccccccc" then your code should return the length of longest character sequence as well the character. In the given String the output should be
'b – 9"

public class LongestStringSequqnce {

    static String myString = "aaaabbbbcccchhhhiiiiibbbbbbbbbccccccc";
    static int largestSequence = 0;
    static char longestChar = '\0';

    public static void main(String args[]) {
        int currentSequence = 1;
        char current = '\0';
        char next = '\0';

        for (int i = 0; i < myString.length() - 1; i++) {
            current = myString.charAt(i);
            next = myString.charAt(i + 1);

            // If character's are in sequence , increase the counter
            if (current == next) {
                currentSequence += 1;
            } else {
                if (currentSequence > largestSequence) { // When sequence is
                                                         // completed, check if
                                                         // it is longest
                    largestSequence = currentSequence;
                    longestChar = current;
                }
                currentSequence = 1; // re-initialize counter
            }
        }
        if (currentSequence > largestSequence) { // Check if last string
                                                 // sequence is longest
            largestSequence = currentSequence;
            longestChar = current;
        }

        System.out.println("Longest character sequence is of character "
                + longestChar + " and is " + largestSequence + " long");
    }

}

Above code is self explanatory. We navigate the String in question Character by Character. If there is a sequence we note its length and move to next. At the end of loop we have with us the longest character sequence length and char with us.

Comments