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 FormatThe first line contains an integer T, i.e. the number of test cases.  The next T lines contain a string each.Output FormatFor 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 || c != chars[top]) {                chars[++top] = c;            } else {                // 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()));        }    }}
Alternating Characters
java;performance;algorithm;strings;programming challenge
No need for stackYou'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 commentThis comment:            // top >= 0 or c == chars[top]should read:            // top >= 0 and c == chars[top]