Search This Blog

Monday, November 10, 2014

Algorithms - Warmup - Alternating Characters

Alternating Characters

The following is the solution to Hacker Rank problem Alternating Characters using Java.  For solutions to other Hacker Rank Problem visit my page HackerRank, alternatively try searching for the problem in my blog.

It is a easy problem, one solution is to read all characters one by one and check if both are equal. If both these characters are equal, we keep count of the character. This count will give us the number of characters to be deleted.

Score:30/30

/**
 *
 */

import java.util.Scanner;

/**
 * @author Arun.G
 *
 */
public class Solution{

       /**
        * @param args
        */
       public static void main(String[] args) {
              // TODO Auto-generated method stub

              Scanner sc = new Scanner(System.in);

              int T = sc.nextInt();
              for (int count = 0; count < T; count++) {
                     char[] characters= sc.next().toCharArray();
                      int AlterCount=0;
                     for(int i=0;i<characters.length-1;i++)
                     {
                           if(characters[i]==characters[i+1])
                           {
                                  AlterCount++;
                           }
                          
                     }
                     System.out.println(AlterCount);
                    
              }

              sc.close();
       }

}

No comments:

Post a Comment

Labels