Java understandable solution. top 10%. Reusable code.


  • 0
    T
    import java.util.Hashtable;
    public class Solution {
    public static char findTheDifference(String str1, String targetStr) {
            Map<Character, Integer> table = new HashMap<>(); //
            StringBuilder resultStr = new StringBuilder("");
            int charCounter;
            for (char currChar : str1.toCharArray()) {
                charCounter = 0;
                if (table.containsKey(currChar)) {
                    charCounter = table.get(currChar);
                }
                table.put(currChar, ++charCounter);
            }
            for (char currChar : targetStr.toCharArray()) {
                Integer count = table.get(currChar);
                if (count == null || count == 0) {
                    resultStr.append(currChar) ;
                } else {
                    table.put(currChar, --count);
                }
            }
              return resultStr.toString().toCharArray()[0];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.