Thursday, June 23, 2016

Alternating Characters -- Number of Deletions

Caution: scanner.next() is the function to read each line in hackerrank.use nextLine()if next() is not working. Hackerrank's input/output methods sucks. very often a right solution is reported as wrong solution.


Number of Deletions


 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 and 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 , i.e. the number of test cases.
The next lines contain a string each.
Output Format
For each test case, print the minimum number of deletions required.
Constraints

length of string
Sample Input
5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB
Sample Output
3
4
0
0
4
Explanation
AAAA A, 3 deletions
BBBBB B, 4 deletions
ABABABAB ABABABAB, 0 deletions
BABABA BABABA, 0 deletions
AAABBB AB, 4 deletions because to convert it to AB we need to delete 2 A's and 2 B's


 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
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        
        for(int i=0;i<n;i++){
            numDeletion(in.next());
        }
    }
    private static void numDeletion(String s){
        if(s==null)
            System.out.println(0);
        if(s.length()==1)System.out.println(0);
        int totalDeletion = 0;
        int i=0,j=1;
        while(j<s.length()){
            while(j<s.length()&&s.charAt(j)==s.charAt(i))
                j++;
            totalDeletion+=j-i-1;
            i=j;
        }
        System.out.println(totalDeletion);
    }
}

No comments: