Posts Remove Consecutive Characters (InterviewBit)
Post
Cancel

Remove Consecutive Characters (InterviewBit)

PROBLEM DESCRIPTION

Given a string A and integer B, remove all consecutive same characters that have length exactly B.

NOTE : All the consecutive same characters that have length exactly B will be removed simultaneously.

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class Solution {

    public String solve(String A, int B) {

        int n = A.length();

        // Counter to keep track of consecutive characters
        int currentCount = 0;

        // Previous character initialized with a non-alphanumeric character
        char prev = '#';

        // StringBuffer to store the result
        StringBuffer res = new StringBuffer();

        // StringBuffer to store consecutive characters temporarily
        StringBuffer temp = new StringBuffer();

        for(int i = 0; i < n; i++){

            // Current character in the iteration
            char ch = A.charAt(i);

            // If the current character is the same as the previous character
            if(ch == prev){

                // Append the character to the temporary StringBuffer
                temp.append(ch + "");

                // Increase the count of consecutive characters
                currentCount++;

            }else{  // If the current character is different from the previous character

                // If there were consecutive characters and their count is not exactly B
                if(currentCount != B){
                    // Append the consecutive characters stored in temp to the result
                    res.append(temp);
                }

                // Reset the temporary StringBuffer with the current character
                temp = new StringBuffer(ch + "");

                // Update the previous character to the current character
                prev = ch;

                // Reset the count of consecutive characters to 1
                currentCount = 1;
            }

        }

        // If there were consecutive characters at the end and their count is not exactly B
        if(currentCount > 0 && currentCount != B){
            // Append the consecutive characters stored in temp to the result
            res.append(temp);
        }

        // Convert the StringBuffer result to a String and return
        return res.toString();
    }
}
This post is licensed under CC BY 4.0 by the author.