Maximum consecutive repeating character in string

package strings;
/**
Maximum consecutive repeating character in string
Given a string, the task is to find maximum consecutive repeating character in string.

Note : We do not need to consider overall count, but the count of repeating that appear at one place.

Examples:

Input : str = "heeeelllo"
Output : e

Input : str = "aaaabbcbbb"
Output : a

**/



public class ConsecutiveRepeating {

    // Returns the maximum repeating character in a
    // given string
    static char maxRepeating(String strin) {
        char[] str = strin.toCharArray();
        int n = strin.length();
        int count = 0;
        char res = str[0];
        int cur_count = 1;

        // Traverse string except last character
        for (int i = 0; i < n - 1; i++) {
            // If current character matches with next
            if (str[i] == str[i + 1])
                cur_count++;

            // If doesn't match, update result
            // (if required) and reset count
            else {
                if (cur_count > count) {
                    count = cur_count;
                    res = str[i];
                }
                cur_count = 1;
            }
        }

        return res;
    }

    public static void main(String[] args) {
        // Driver code
        String str = "aaaabbaaccde";
        System.out.println(maxRepeating(str));
    }


}

Comments

Popular posts from this blog

Java important topics list for interviews

Tough Sql practise questions for interviews involving SELECT queries - Part 2

DBMS important topics list for interviews

Program to find number lines and words in a given file

Tough Sql practise questions for interviews involving SELECT queries - Part 1

Producer Consumer Problem with Blocking Queue in Java.

Animation for String search - KMP Algorithm

Interactive Data Structure visualizations/animations for algorithms

Replace Occurances of the given string