public class Solution{
public static char findTheDifference(String s, String t){
HashMap<Character, Integer> map = new HashMap<>();
for(Character ch : s.toCharArray()){
map.put(ch, map.getOrDefault(ch, 0)+1);
}
for(Character ch: t.toCharArray()){
if(map.containsKey(ch) && map.get(ch)>0){
map.put(ch, map.get(ch)-1);
if(map.get(ch) == 0){
map.remove(ch);
}
}else{
return ch;
}
}
return ' ';
}
}```
Is there any other method to do this other than Hashmap
#check my code
7 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @cinder summit! Please use
/closeor theClose Postbutton above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 720 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
There are better methods than put(key, get(key)+1):
map.merge(key, 1, Integer::sum);
Also there is collect(Collectors.groupingBy(c -> c, Collectors.counting())) on the character stream (chars()).
If you know the range of the input characters beforehand (e.g. only lowercase ascii) you could also just use an array for counting.
