Count Occurrence of Characters in a String: This Java program takes an input string “AAAABBCCCDDDDEEEG” and generates an output string “A4B2C3D4E3G1”. The program compresses the input string by representing each character and the number of occurrences of that character consecutively.
Count Occurrence of Characters in a String
package com.softwaretestingo.interviewprograms; import java.util.ArrayList; public class InterviewPrograms19 { /* * Input string "AAAABBCCCDDDDEEEG" * Output string "A4B2C3D4E3G1" */ public static void main(String[] args) { String s ="AAAABBCCCDDDDEEEG"; ArrayList<Character> list = new ArrayList<>(); for(int i=0;i<s.length();i++) { int count=1; if(!list.contains(s.charAt(i))) { list.add(s.charAt(i)); for(int j=i+1;j<s.length();j++) { if(s.charAt(i)==s.charAt(j)) { count++; } } System.out.print(s.charAt(i)+""+count); } } } }
Output
A4B2C3D4E3G1
Let’s break down the program step by step for Java beginners:
- Package and Import Statements:
- The program is part of the package com.softwaretestingo.interviewprograms.
- It imports the ArrayList class from the java.util package to use dynamic arrays.
- Class and main() Method:
- The program defines a class called InterviewPrograms19.
- It contains a main method, the entry point of the program, which will be executed first.
- Input String:
- String s = “AAAABBCCCDDDDEEEG”;: This line declares and initializes the input string s with the value “AAAABBCCCDDDDEEEG”.
- ArrayList Initialization:
- ArrayList<Character> list = new ArrayList<>();: An ArrayList called list is created to store unique characters encountered in the input string.
- Looping through the Input String:
- for(int i=0; i<s.length(); i++) { … }: The program uses a for loop to iterate over each character of the input string.
- Character Counting:
- int count = 1;: A variable count is initialized to 1 to count the occurrences of the current character.
- Checking for Unique Characters:
- if (!list.contains(s.charAt(i))) { … }: This if condition checks if the current character is not present in the list, which means it’s a new character.
- Adding Unique Characters to the List and Counting Occurrences:
- list.add(s.charAt(i));: If the character is unique, it’s added to the list.
- The program then uses another for loop (nested within the first loop) to find the number of occurrences of this unique character by comparing it with the remaining characters in the string.
- Printing the Compressed Output:
- System.out.print(s.charAt(i) + “” + count);: After counting the occurrences of the current unique character, it’s printed along with its count.
- Output:
- The output of the program will be “A4B2C3D4E3G1”, which represents the compressed version of the input string “AAAABBCCCDDDDEEEG”.
In summary, this Java program takes an input string, compresses it by counting consecutive occurrences of each character, and then prints the compressed version of the string.
Alternative 1:
This Java program achieves the same goal as the previous one, which is to compress an input string “AAAABBCCCDDDDEEEG” into an output string “A4B2C3D4E3G1”. However, it uses a different approach to achieve this compression.
package com.softwaretestingo.interviewprograms; import java.util.HashMap; import java.util.Map; public class InterviewPrograms19_1 { /* * Input string "AAAABBCCCDDDDEEEG" * Output string "A4B2C3D4E3G1" */ public static void main(String[] args) { String s = "AAAABBCCCDDDDEEEG"; String[] sArray = s.split(""); Map<String, Integer> map = new HashMap<>(); for(String temp : sArray) { if(map.containsKey(temp)) { map.put(temp, map.get(temp)+1); } else { map.put(temp, 1); } } System.out.println(map.toString().replaceAll("\\W","")); } }
Output
A4B2C3D4E3G1
Let’s break down the program section by section for Java beginners:
- Package and Import Statements:
- The program is part of the package com.softwaretestingo.interviewprograms.
- It imports the HashMap and Map classes from the java.util package to work with key-value pairs.
- Class and main() Method:
- The program defines a class called InterviewPrograms19_1.
- It contains a main method, the entry point of the program, which will be executed first.
- Input String:
- String s = “AAAABBCCCDDDDEEEG”;: This line declares and initializes the input string s with the value “AAAABBCCCDDDDEEEG”.
- Splitting the Input String:
- String[] sArray = s.split(“”);: The input string s is split into an array of individual characters using the split(“”) method.
- Creating a HashMap:
- Map<String, Integer> map = new HashMap<>();: A HashMap called map is created to store characters as keys and their occurrences as values.
- Looping through the Input Characters:
- for(String temp : sArray) { … }: The program uses an enhanced for loop to iterate over each character in the sArray.
- Counting Character Occurrences:
- if(map.containsKey(temp)) { … }: It checks if the current character (temp) is already present in the map.
- Updating the HashMap:
- If the character is already in the map, its corresponding value (occurrence count) is incremented by one.
- If the character is not present in the map, it’s added to the map with an initial occurrence count of 1.
- Printing the Compressed Output:
- System.out.println(map.toString().replaceAll(“\\W”,””));: After counting occurrences of all characters, the program prints the compressed output.
- map.toString() converts the map to a string representation (e.g., “{A=4, B=2, C=3, D=4, E=3, G=1}”).
- .replaceAll(“\\W”,””) removes all non-word characters (non-alphanumeric characters) from the string, resulting in the desired compressed output “A4B2C3D4E3G1”.
In summary, this Java program compresses the input string by counting the occurrences of each character using a HashMap, and then it prints the compressed output in the format “A4B2C3D4E3G1”.
Alternative 2:
This Java program also achieves the goal of compressing the input string “AAAABBCCCDDDDEEEG” into the output string “A4B2C3D4E3G1”. It uses a HashMap to count the occurrences of each character in the input string and then prints the compressed output.
package com.softwaretestingo.interviewprograms; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class InterviewPrograms19_2 { /* * Input string "AAAABBCCCDDDDEEEG" * Output string "A4B2C3D4E3G1" */ public static void main (String [] args) { String str = "AAAABBCCCDDDDEEEG"; occurences (str); } public static void occurences(String str) { int count = 0 ; Map <Character, Integer> hs=new HashMap <Character ,Integer>(); for ( int i = 0 ; i<str.length(); i++) { if ( hs.containsKey(str.charAt(i))) { count =hs.get(str.charAt(i)); count = count+1; hs.put(str.charAt(i),count); } else { hs.put(str.charAt(i), 1); } } Set<Map.Entry <Character, Integer>> s = hs.entrySet(); for (Entry<Character,Integer> s1 : s ) { System.out.print (s1.getKey()+ ""+s1.getValue()); } } }
Output
A4B2C3D4E3G1
Let’s break down the program section by section for Java beginners:
- Package and Import Statements:
- The program is part of the package com.softwaretestingo.interviewprograms.
- It imports several classes from the java.util package, including HashMap, Map, Entry, and Set, which are used for handling key-value pairs.
- Class and main() Method:
- The program defines a class called InterviewPrograms19_2.
- It contains a main method, the entry point of the program, which will be executed first.
- Input String:
- String str = “AAAABBCCCDDDDEEEG”;: This line declares and initializes the input string str with the value “AAAABBCCCDDDDEEEG”.
- Calling the occurences() Method:
- occurences(str);: The program calls the occurences() method, passing the input string str to it for processing.
- occurences() Method:
- public static void occurences(String str) { … }: This method takes a string as input and is responsible for counting the occurrences of each character.
- Initializing the HashMap:
- Map<Character, Integer> hs = new HashMap<Character, Integer>();: A HashMap called hs is created to store characters as keys and their occurrences as values.
- Looping through the Input Characters:
- The program uses a for loop to iterate over each character in the input string str.
- Counting Character Occurrences using HashMap:
- If the character is already present in the hs HashMap, the program retrieves its current count, increments it by one, and puts the updated count back into the hs.
- If the character is not present in the hs HashMap, it is added to the hs with an initial count of 1.
- Printing the Compressed Output:
- Set<Map.Entry<Character, Integer>> s = hs.entrySet();: The program gets the entry set of the hs HashMap to iterate over its key-value pairs.
- Looping through HashMap Entries and Printing:
- The program uses an enhanced for loop to iterate over each entry (s1) in the entry set s.
- It then prints the key (character) and value (occurrence count) of each entry, resulting in the compressed output format “A4B2C3D4E3G1”.
In summary, this Java program also compresses the input string by counting the occurrences of each character using a HashMap, and then it prints the compressed output in the format “A4B2C3D4E3G1”.
Leave a Reply