Alternating Characters 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 &lt; 0 || c != chars[top]) {
                chars[++top] = c;
            } else {
                // top &gt;= 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 &lt; N; i++) {
            System.out.println(countChanges(s.next()));
        }
    }
}
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 &gt;= 0 or c == chars[top]



should read:

            // top &gt;= 0 and c == chars[top]