-3

I am trying to figure out how to count the occurrences of a certain character in String such that the consecutive occurrence is considered as one. Like in string "PPPPAPAAPP" the occurrence of P as 3 and A as 2.

Dinesh Neupane
  • 382
  • 10
  • 19

3 Answers3

1

I think this will help you,

   import java.util.*;

      public class MyClass {
       public static void main(String args[]) {
             Map<String,Integer> countMap = new HashMap<String,Integer>();
             String s = "PPPPPAAPAP";
             String prev = null;
             for(int i=0;i<s.length();i++){
              String c = String.valueOf(s.charAt(i));
              if(prev==null){
                countMap.put(c,new Integer(1));
              }else{
              if(!c.equals(prev)){

                if(countMap.containsKey(c)){

                      Integer count = countMap.get(c);
                      count = count +1;
                      countMap.put(c,count);

                }
               else{

                     countMap.put(c,new Integer(1));

               }
            }
        }
        prev = c;
      }
      for(String keys :countMap.keySet()){
        System.out.println("Keys:"+keys+"\t"+countMap.get(keys));
      }
     }
    }
Saranya Subramanian
  • 417
  • 1
  • 5
  • 19
0

This shows your total correctly:

 public static void main (String Args[]){
Scanner in =new Scanner(System.in);
String s =in.next();
//HashSet hd =new HashSet();
int flag=0;
int count=1;
char a=s.charAt(0);
for(int i=1;i<s.length();i++)
{
    //hd.add(s.charAt(i));
    if(a==s.charAt(i))
    {
        continue;
    }
    else
    {
        a=s.charAt(i);
        count++;
    }
}
System.out.println(count);
        }
Lalit Verma
  • 782
  • 10
  • 25
0

If you have to cound only letters or e.g. limit range of ASCII, then you could avoid using Map:

public static void main(String... args) {
    int[] letters = calcLetterGroups("PPPPPAAPAP");
    printExistedLetterGroups(letters);
}

public static int[] calcLetterGroups(String str) {
    int[] arr = new int['Z' - 'A' + 1];
    char prv = '\0';

    for (char ch : str.toUpperCase().toCharArray()) {
        if (ch >= 'A' && ch <= 'Z' && prv != ch) {
            arr[ch - 'A']++;
            prv = ch;
        }
    }

    return arr;
}

public static void printExistedLetterGroups(int... letters) {
    for (char ch = 'A'; ch <= 'Z'; ch++)
        if (letters[ch - 'A'] > 0)
            System.out.printf("%s: %d\n", String.valueOf(ch), letters[ch - 'A']);
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35