Least repeating chararcter in a string - java

I'm trying to find the least repeating character in a string ,it works for some input but it fails for some input.
Map<Character, Integer> map = new HashMap<Character, Integer> ();
String s = "abcdabcdabcdacd";
char[] chars = s.toCharArray();
for (Character ch: chars) {
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
map.put(ch, 1);
}
}
Set<Character> keys = map.keySet();
for (Character ch: keys) {
if (map.get(ch) ==1) {
System.out.println(ch + " ");
}
}
I expect the output to be b but it doesn't show anything.
If i give aabaa as the input then it shows b and that's correct.

As I commented already, you only check for characters which only occur once, not for the least occurrence.
You can change your code by this:
public class PrintB {
public static void main(String[] args) {
Map<Character, Integer> map = new HashMap<>();
String s = "abcdabcdabcdacd";
char[] chars = s.toCharArray();
for (Character ch: chars) {
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
map.put(ch, 1);
}
}
Set<Character> keys = map.keySet();
boolean broken = false;
for ( int i = 0; i < s.length(); i++ ) { // the max will be s.length()
for (Character ch : keys) {
if (map.get(ch) == i) { // this amount is checked for each char
System.out.println(ch + " ");
broken = true;
}
}
if ( broken ) {
i = s.length(); // sure, there are other ways to break out of the loop
}
}
}
}

Using streams you may simply do:
final String s = "abcdabcdabcdacd";
String leastRepeated =
s.chars().mapToObj(i -> Character.toString((char) i)) // map to Stream<String>
.collect(Collectors.toMap(k -> k, v -> 1, Integer::sum)) // Map<String, Integer>
.entrySet().stream() // stream over map
.min(Comparator.comparing(Entry::getValue)) // comparing values in map
.get().getKey(); // get resp entry
which outputs:
b

You have to read the whole map to get the min occurrence, so you can't print in the loop, you should instead collect chars with min occurence, and then print them.
public static void main(String[] args) {
Map<Character, Integer> map = new HashMap<>();
String s = "abcdaybcdabcdacdz";
char[] chars = s.toCharArray();
for (Character ch: chars) {
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
map.put(ch, 1);
}
}
List<Character> reps = new ArrayList<>();
Integer count = chars.length;
Set<Entry<Character, Integer>> entries = map.entrySet();
for (Entry<Character, Integer> entry : entries) {
Integer n = entry.getValue();
Character c = entry.getKey();
if(n==count) {
reps.add(c);
}else if (n<count) {
reps = new ArrayList<>();
reps.add(c);
count = n;
}
}
for (Character character : reps) {
System.out.println(character);
}
}

The reason your code doesn't work the way you would want it to is because your last code block is only printing if the character is being repeated once and only once:
for (Character ch: keys) {
if (map.get(ch) ==1) {
System.out.println(ch + " ");
}
However by using the Collections.min method we can find the lowest map value which we can then use to find the character it belongs to from map keys. Here is the complete code with context:
/**
* #return an array of Character objects that have occured the
* least amount of times in the given {#code String} parameter.
* <i>Note that all whitespaces found within the {#code String} will be ignored </i>
*/
public static Character[] getLeastRepeatingCharacters(String text) {
Map<Character, Integer> map = new HashMap<Character, Integer> ();
/*
* Remove all whitespaces from the text as we don't
* want to include them in our comparison oprations
*/
text = text.replaceAll("\\s+","");
for (Character ch : text.toCharArray()) {
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
}
else if (ch != '\0') {
map.put(ch, 1);
}
}
/*
* Get map value that occurs the least amount of times
*/
int leastOccuranceValue = Collections.min(map.values());
java.util.List<Character> leastOccurances = new java.util.ArrayList<>();
/*
* Iterate through the map, find all characters that have
* occured the least amount of times and add them to a list
*/
for (java.util.Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue().equals(leastOccuranceValue)) {
leastOccurances.add(entry.getKey());
}
}
return leastOccurances.toArray(new Character[0]);
}
public static void main(String[] args) {
String text = "abcdabcdabcdacd";
Character[] leastRepeating = getLeastRepeatingCharacters(text);
String log = "Array of charactes that repeated the least amount of times in text '%s':%n%s";
System.out.printf(log, text, Arrays.toString(leastRepeating));
}
Output:
Your string sample:
Array of charactes that repeated the least amount of times in text 'abcdabcdabcdacd ':
[b]
String sample provided by Stultuske:
Array of charactes that repeated the least amount of times in text 'kambcxdabcdalbcdacd ':
[x, k, l, m]

Related

Hashset contains with exact character placement and incorrect character placement

I have a class that determines how many matching characters are in 2 char arrays. Using the HashSet contains method, if one char array contains a Character from the second array, display the character.
The problem is if we have two matching characters appearing in multiple locations.
For example, if array 1 = adcd and array 2 = a05ddd, d appears 3 times, not 2.
How would I modify this to account for the correct character count? The code produces "addd" when it should produce "add"
For the incorrect characters, the result would be
"a--dd"
HashSet<Character> hash = new HashSet<Character>();
String word1 = "adcd";
String word2 = "a05ddd";
char[] ch1 = word1.toCharArray();
char[] ch2 = word2.toCharArray();
Character character = null;
String charLocation = "";
int count = 0;
for (int i = 0; i < ch1.length; i++)
{
hash.add(ch1[i]);
}
for (int i = 0; i < ch2.length; i++)
{
character = ch2[i];
if (hash.contains(character))
{
charLocation = charLocation + character;
count++;
}
if (!hashSet.contains(character))
correctCharPlacements = correctCharPlacements + "-";
}
It is very likely that the data about the frequency of the characters needs to be collected -- so set should be replaced with a map. Then the resulting string may be built with regard to common characters and minimal frequency of the character in both words:
// helper method to build frequency map for a word/string
private static Map<Character, Integer> freqMap(String word) {
return word.chars()
.mapToObj(c -> (char)c)
.collect(Collectors.toMap(x -> x, x -> 1, Integer::sum, LinkedHashMap::new));
}
static String common(String w1, String w2) {
if (null == w1 || null == w2) {
return null;
}
Map<Character, Integer> map1 = freqMap(w1);
Map<Character, Integer> map2 = freqMap(w2);
Set<Character> commonChars = new LinkedHashSet<>(map1.keySet());
commonChars.retainAll(map2.keySet());
return commonChars.stream()
.map(x -> String.valueOf(x).repeat(Math.min(map1.get(x), map2.get(x))))
.collect(Collectors.joining(""));
}
Test:
System.out.println("common = " + common("adcd", "a05ddd"));
Output:
common = add
Update
As String::repeat is available starting from Java 11, it may be replaced with the Java 8 compatible code using String::join + Collections.nCopies:
static String common(String w1, String w2) {
if (null == w1 || null == w2) {
return null;
}
Map<Character, Integer> map1 = freqMap(w1);
Map<Character, Integer> map2 = freqMap(w2);
Set<Character> commonChars = new LinkedHashSet<>(map1.keySet());
commonChars.retainAll(map2.keySet());
return commonChars.stream()
.map(x -> String.join("", Collections.nCopies(Math.min(map1.get(x), map2.get(x)), String.valueOf(x))))
.collect(Collectors.joining(""));
}
Online demo:
System.out.println("Java version: " + System.getProperty("java.version"));
System.out.println("common = " + common("adcd", "a05ddd"));
Output:
Java version: 1.8.0_201
common = add
Update 2
In order to keep the order of the characters in the second string in the result and replace missing characters with '-', the following method can be implemented:
static String common2(String w1, String w2) {
if (null == w1 || null == w2) {
return null;
}
Map<Character, Integer> map1 = freqMap(w1);
StringBuilder sb = new StringBuilder();
for (char c : w2.toCharArray()) {
if (map1.containsKey(c) && map1.get(c) > 0) {
sb.append(c);
map1.merge(c, -1, Integer::sum); // decrement the character counter in the first map
} else if (!map1.containsKey(c)) { // character missing in the first word
sb.append('-');
}
}
return sb.toString();
}
Tests
String[][] tests = {
{"adcd", "ad05dd"},
{"adcd", "d05add"},
{"adcd", "d05dadd"},
};
for (String[] test : tests) {
System.out.printf("common(%s, %s) = %s%n", test[0], test[1], common(test[0], test[1]));
}
Output:
common(adcd, ad05dd) = ad--d
common(adcd, d05add) = d--ad
common(adcd, d05dadd) = d--da

Problems with sorting the characters of a word

I have a problem that I have been struggling with for some time.
I am given a word consisting of small or large letters of the English alphabet, to sort the characters so that in the first positions appear the characters that appear most often in the word, and if they appear by the same number of times, they will be sorted lexicographical.
Such as:
input:
Instructions
output:
iinnssttcoru
So far I have written this, but from here I do not know how to sort them and display properly, a tip?
public class Main {
public static void main(String[] args) throws IOException {
String testString = " ";
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
testString = rd.readLine();
Map<Character, List<Character>> map = new HashMap<>();
for (int i = 0; i < testString.length(); i++) {
char someChar = testString.charAt(i);
if (someChar == ' ') {
continue;
}
char ch = testString.charAt(i);
List<Character> characters = map.getOrDefault(Character.toLowerCase(ch), new ArrayList<>());
characters.add(ch);
map.put(Character.toLowerCase(ch), characters);
}
List<Map.Entry<Character, List<Character>>> list = new ArrayList<>(map.entrySet());}
You can add TreeMap counterAppear with the key is the number of repetitions of the character and value is a list of characters has the same number of key repetitions. This list needs to be sorted before printing to ensure the order as required. Use TreeMap to make sure the map is sorted by key(the number of repetitions).
public static void main(String[] args) throws IOException {
String testString = " ";
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
testString = rd.readLine();
Map<Character, List<Character>> map = new HashMap<>();
for (int i = 0; i < testString.length(); i++) {
char someChar = testString.charAt(i);
if (someChar == ' ') {
continue;
}
char ch = testString.charAt(i);
//Change to Optimize Code
Character keyCharacter = Character.toLowerCase(ch);
if (map.get(keyCharacter) == null) {
map.put(keyCharacter, new ArrayList<>());
}
List<Character> characters = map.get(keyCharacter);
characters.add(ch);
}
TreeMap<Integer, List<Character>> counterAppear = new TreeMap<>();
for (Map.Entry<Character, List<Character>> entry : map.entrySet()) {
Character character = entry.getKey();
int repeatCharTime = entry.getValue().size();
if (counterAppear.get(repeatCharTime) == null) {
counterAppear.put(repeatCharTime, new ArrayList<>());
}
List<Character> characters = counterAppear.get(repeatCharTime);
characters.add(character);
}
for (Integer repeatCharTime : counterAppear.descendingKeySet()) {
List<Character> keyCharacters = counterAppear.get(repeatCharTime);
Collections.sort(keyCharacters);
for (Character character : keyCharacters) {
for (int i = 0; i < repeatCharTime; i++) {
System.err.print(character);
}
}
}
}
Here's my solution:
import java.util.*;
public class Test
{
static void process(String s)
{
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
for(Character c : s.toLowerCase().toCharArray())
{
Integer nb = map.get(c);
map.put(c, nb==null ? 1 : nb+1);
}
ArrayList<Map.Entry<Character,Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, (a,b) ->
{
int res = b.getValue().compareTo(a.getValue());
if(res!=0)
return res;
return a.getKey().compareTo(b.getKey());
});
for(Map.Entry<Character,Integer> e : list)
{
for(int i=0;i<e.getValue();i++)
System.out.print(e.getKey());
}
}
public static void main(String[] args)
{
process("Instructions");
}
}

Sort by number of apearances

for example, I am given a word and I have to sort its letters by the number of occurrences in that word, if 2 letters appear the same number of times it will be sorted by the lexicographic minimum.
For now, I have started to see how many times a letter appears in a word but from here I do not know exactly how to do it.
The problem requires me to use BufferedReader and BufferedWriter.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<Character, Integer> m = new HashMap<>();
String s = sc.nextLine();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (m.containsKey(c))
m.put(c, m.get(c) + 1);
else
m.put(c, 1);
}
for (char letter = 'a'; letter <= 'z'; ++letter)
if (m.containsKey(letter))
System.out.println(letter + ": " + m.get(letter));
}
For the moment I am posting what letters appear most often in the word, but I do not know how to sort them by the number of occurrences and in case there are two letters that appear at the same number of times with the minimum lexicographic.
I hope this is what you want
public static void main(String[] args) {
Map<Character, Integer> m = new HashMap<>();
String testString = "Instructions";
Map<Character, List<Character>> map = new HashMap<>();
for (int i = 0; i < testString.length(); i++) {
char someChar = testString.charAt(i);
if (someChar == ' ') {
continue;
}
char ch = testString.charAt(i);
List<Character> characters = map.getOrDefault(Character.toLowerCase(ch), new ArrayList<>());
characters.add(ch);
map.put(Character.toLowerCase(ch), characters);
}
List<Map.Entry<Character, List<Character>>> list = new ArrayList<>(map.entrySet());
list.sort((o1, o2) -> {
if (o1.getValue().size() == o2.getValue().size()) {
return o1.getKey() - o2.getKey();/// your lexicographic comparing
}
return o2.getValue().size() - o1.getValue().size();
});
list.forEach(entry -> entry.getValue().forEach(System.out::print));
}
To count letters in word, you can use much simpler method:
define array with 26 zeros, scan input line and increase appropriate index in this array, so if you meet 'a' (or 'A' - which is the same letter, but different symbol) - you will increase value at index 0, b - index 1, etc
during this scan you can also compute most occurred symbol, like this:
public static void main(final String[] args) throws IOException {
char maxSymbol = 0;
int maxCount = 0;
final int[] counts = new int[26]; // number of times each letter (a-z) appears in string
try (final BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
final String s = br.readLine().toLowerCase(); // calculate case-insensitive counts
for (final char c : s.toCharArray()) {
final int idx = c - 'a'; // convert form ASCII code to 0-based index
counts[idx]++;
if (counts[idx] > maxCount) {
maxSymbol = c; // we found most occurred symbol for the current moment
maxCount = counts[idx];
} else if (counts[idx] == maxCount) { // we found 2nd most occurred symbol for the current moment, need to check which one is minimal in lexicographical order
if (c < maxSymbol) {
maxSymbol = c;
}
}
}
}
if (maxSymbol > 0) {
System.out.println("Most frequent symbol " + maxSymbol + " occurred " + maxCount);
}
}
I've used buffered reader to get data from stdin, but I have no idea where to put buffered writer here, maybe to print result?

A program that counts the letters in string in Java

I have to create a program that counts the letters in string and I have a little problem with that.
This is my code in main:
Scanner sc = new Scanner(System.in);
String str;
int count;
System.out.println("Enter some text: ");
str = sc.nextLine();
char ch;
System.out.println("Letters: ");
for (ch = (char) 65; ch <= 90; ch++) {
count = 0;
for (int i = 0; i < str.length(); i++) {
if (ch == str.charAt(i) || (ch + 32) == str.charAt(i)) {
count++;
}
}
if (count > 0) {
System.out.println(ch + ": " + count);
}
}
Everything looks fine, but the output should not be in alphabetical order, rather ordered by the number of letters descending.
For example, if you input Hello World, the output should be something like this:
L: 3
O: 2
H: 1
D: 1
E: 1
R: 1
W: 1
The output would be sorted in descending order of letter frequency. That means the most frequent letter should appear first and the least last.
The order for letters that appears in equal proportions must be in alphabetical order.
The problem is that your outer loop browse the letters in alphabetical order, and that's where you display the count.
I would instead recommend browsing the input string with a single loop, updating the count of each letter in a Map<Character, Integer> as I encounter them.
Then once the input String has been consumed, I would sort the Map by descending values, and print each key/value pair.
Map<Character, Integer> lettersCount = new HashMap<>();
for (int i=0; i <str.length(); i++) {
Character current = str.charAt(i);
if (Character.isLetter(current)) {
Integer previousCount = lettersCount.get(current);
if (previousCount != null) {
lettersCount.put(current, previousCount + 1);
} else {
lettersCount.put(current, 1);
}
}
}
List<Map.Entry<Character, Integer>> list = new LinkedList<Map.Entry<Character, Integer>>( lettersCount.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<Character, Integer>>()
{
public int compare( Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2 )
{
return (o2.getValue()).compareTo( o1.getValue() );
}
} );
for (Map.Entry<Character, Integer> entry : list) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
You can try it out on ideone.
As you can see, sorting a Map by values isn't trivial :-/
If you want to sort the results then you'll have to store the results & then iterate over them by their count descending to print in order
The best data structure to store them into would be a heap, keyed off of count. Java supplies such a data structure as java.util.PriorityQueue which can take a comparator function which first compares count & then character
https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str;
int count;
System.out.println("Enter some text: ");
str = sc.nextLine();
char ch;
System.out.println("Letters: ");
LinkedHashMap<String, Integer> charCountMap = new LinkedHashMap<String, Integer>();
for (ch = (char) 65; ch <= 90; ch++) {
count = 0;
for (int i = 0; i < str.length(); i++) {
if (ch == str.charAt(i) || (ch + 32) == str.charAt(i)) {
count++;
}
}
if (count > 0) {
System.out.println(ch + ": " + count);
charCountMap.put(ch + "", count);
}
}
LinkedHashMap<String, Integer> sortedMapBasedOnValues = sortHashMapByValues(charCountMap);
for (Map.Entry<String, Integer> entry : sortedMapBasedOnValues.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
// Following method used from
// http://stackoverflow.com/questions/8119366/sorting-hashmap-by-values
public static LinkedHashMap<String, Integer> sortHashMapByValues(LinkedHashMap<String, Integer> passedMap) {
List<String> mapKeys = new ArrayList<>(passedMap.keySet());
List<Integer> mapValues = new ArrayList<>(passedMap.values());
Collections.sort(mapValues, Collections.reverseOrder());
Collections.sort(mapKeys);
LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
Iterator<Integer> valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
Integer val = valueIt.next();
Iterator<String> keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
String key = keyIt.next();
Integer comp1 = passedMap.get(key);
Integer comp2 = val;
if (comp1.equals(comp2)) {
keyIt.remove();
sortedMap.put(key, val);
break;
}
}
}
return sortedMap;
}
}

Arranging word to formpalindrome

Hello i´ve been trying to form palindromes from this input:
String[] text ={"ivcci", "oyotta", "cecarar","bbb","babbbb"};
getPalindrome(text);
and i need to rearrange all words in array to produce this output
civic
-1
rececar
bbb
bbabb
the method expects to receive an array of Strings like
public static String getPalindrome(String[] text){}
"returning -1 means i.g "oyotta" in array can´t form a palíndrome
i´ve been testing this code and it works but i.g "cecarar" is not producing "racecar", as im a bit new in java i used an String intead an array of Strings, can anybody help to write this code properly please?
Thanks a lot!
public static String getPalindrome(String s) {
if (s == null)
return null;
Map<Character, Integer> letters = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!letters.containsKey(c))
letters.put(c, 1);
else
letters.put(c, letters.get(c) + 1);
}
char[] result = new char[s.length()];
int i = 0, j = result.length - 1;
Character middle = null;
for (Entry<Character, Integer> e : letters.entrySet()) {
int val = e.getValue();
char c = e.getKey();
if (val % 2 != 0) {
if (middle == null && s.length() % 2 != 0) {
middle = c;
val--;
} else
return "-1";
}
for (int k = 0; k < val / 2; k++) {
result[i++] = c;
result[j--] = c;
}
}
if (middle != null)
result[result.length / 2] = middle;
return new String(result);
}
In order for a set of characters to be able to produce a palindrome, only one of the letters can be repeated an odd number of times, so you can first weed that out.
Without writing actual code for you, here is the algorithm I would use:
Create a map of characters to a counter. Possible to do int[] counts = new int[26];
Go through each character in the input string, and increment the count: ++counts[Character.toLower(c)-'a'];
Then go through each character, and see if its odd if (counts[i] & 1 != 0) { if (oddIndex != -1) { return -1; } oddIndex=i; } This will return -1 if there is two or more odd counts.
Then, you can create a StringBuilder, and start with the oddIndex in the middle, if it exists.
Then go through the counts, and add count[i]/2 to the front and back of your string builder.
That'll give you a symmetric string from the original inputs.
Now, if you actually need words, then you'll have to have a dictionary of palindromes. You can actually preprocess all the palindromes to have a map of "sorted character string"=>"palindrome"
class PalindromeChecker
{
final Map<String, String> palindromes = new HashMap<String, String>();
public PalindromeChecker(Iterable<String> allPalindromes) {
for (String palindrome: allPalindromes) {
char[] chars = palindrome.getChars();
Arrays.sort(chars);
palindromes.put(String.valueOf(chars), palindromes);
}
}
public String getPalindrome(String input) {
char[] chars = input.getChars();
Arrays.sort(chars);
return palindromes.get(String.valueOf(chars));
}
}
As other users pointed out, a string can be rearranged as a palindrome only if there is at most one character that appears an odd number of times.
Once you have confirmed that a string can be converted to a palindrome, you can construct the palindrome as follows (this is just one of many methods of course):
place at the sides of the string all the pairs of characters that you can get
place at the middle of the string the single character that is left out, in case there is such a character.
Example:
public class Palindromes {
public static void main(String[] args) {
String[] text = {"ivcci", "oyotta", "cecarar","bbb","babbbb"};
for(String str : text){
evaluatePalindrome(str);
}
}
private static void evaluatePalindrome(String str){
PalindromeCandidate pc = new PalindromeCandidate(str);
if(pc.isPalindrome()){
System.out.println(pc.getPalindrome());
} else {
System.out.println("-1");
}
}
}
public class PalindromeCandidate {
private final CharacterCount characterCount;
public PalindromeCandidate(String originalString) {
this.characterCount = new CharacterCount(originalString);
}
public boolean isPalindrome(){
Collection<Integer> counts = characterCount.asMap().values();
int oddCountOccurrences = 0;
for(Integer count : counts){
oddCountOccurrences += (count%2);
}
return (oddCountOccurrences <= 1);
}
public String getPalindrome(){
if(!isPalindrome()){
throw new RuntimeException("Cannot be rearranged as a palindrome.");
}
Map<Character, Integer> counts = characterCount.asMap();
StringBuilder leftSide = new StringBuilder();
StringBuilder middle = new StringBuilder();
for(Character ch : counts.keySet()){
int occurrences = counts.get(ch);
while(occurrences > 1){
leftSide.append(ch);
occurrences -= 2;
}
if(occurrences > 0){
middle.append(ch);
}
}
StringBuilder rightSide = new StringBuilder(leftSide).reverse();
return leftSide.append(middle).append(rightSide).toString();
}
}
/**
* Thin wrapper around a Map<Character, Integer>. Used for counting occurences
* of characters.
*/
public class CharacterCount {
private final Map<Character, Integer> map;
public CharacterCount(String str) {
this.map = new HashMap<>();
for(Character ch : str.toCharArray()){
increment(ch);
}
}
private void increment(Character ch){
this.map.put(ch, getCount(ch) + 1);
}
private Integer getCount(Character ch){
if(map.containsKey(ch)){
return map.get(ch);
} else {
return 0;
}
}
public Map<Character, Integer> asMap(){
return new HashMap<>(map);
}
}

Categories

Resources