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

Alternating Characters

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

Problem

Online challenge on Hacker Rank.


Shashank likes strings in which consecutive characters are different.
For example, he likes ABABA, while he doesn't like ABAA. Given a
string containing characters A and B only, he wants to change it
into a string he likes. To do this, he is allowed to delete the
characters in the string.


Your task is to find the minimum number of required deletions.


Input Format


The first line contains an integer T, i.e. the number of test cases.
The next T lines contain a string each.


Output Format


For each test case, print the minimum number of deletions required.

public class Solution {
    private static int countChanges(String text) {
        char[] chars = new char[text.length()];
        int top = -1;

        int count = 0;
        for (char c : text.toCharArray()) {
            if (top = 0 or c == chars[top]
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int N = s.nextInt();
        for (int i = 0; i < N; i++) {
            System.out.println(countChanges(s.next()));
        }
    }
}

Solution

No need for stack

You've complicated things by constructing a stack for no reason. All you need to remember is the last character. For example:

private static int countChanges(String text) {
    char prev  = 0;
    int  count = 0;

    for (char c : text.toCharArray()) {
        if (c == prev) {
            count++;
        } else {
            prev = c;
        }
    }
    return count;
}


Misleading comment

This comment:

// top >= 0 or c == chars[top]


should read:

// top >= 0 and c == chars[top]

Code Snippets

private static int countChanges(String text) {
    char prev  = 0;
    int  count = 0;

    for (char c : text.toCharArray()) {
        if (c == prev) {
            count++;
        } else {
            prev = c;
        }
    }
    return count;
}
// top >= 0 or c == chars[top]
// top >= 0 and c == chars[top]

Context

StackExchange Code Review Q#151023, answer score: 3

Revisions (0)

No revisions yet.