4
\$\begingroup\$

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 || 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())); } } } 
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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] 
\$\endgroup\$
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.