easy Java O(n) solution using map

  • 1

    Hi, guys.
    It's more slower than other cool solutions, anyway It's still worth consideration.

    For example,
    s = "asdff"
    t = "sfasdf" // one more 's'

    1. Store characters in s string to Map using for loop.
      Key is the character and Value is number of the character.
      (after this loop, we got the map (a->1), (s->1), (d->1), (f->2).)

    2. Iterate t string. In this time, Let's 'subtract' value of the map using character of t string.
      If value will be lower than zero or there's no key, it means that's the element we have to find.
      In example case,
      i=0, key:s, value:1 ->0
      i=1, key:f, value:2 -> 1
      i=2, key:a, value:1 -> 0
      i=3, key:s, value:0 -> -1 detect & return 's'.

    Here's my code and Happy coding y'all:)

    public char findTheDifference(String s, String t) {
    	HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    	for (int i = 0; i < s.length(); i++) {
    		map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
    	for (int i = 0; i < t.length(); i++) {
    		int value = map.getOrDefault(t.charAt(i), 0) -1;
    		if(value < 0) return t.charAt(i);
    		map.put(t.charAt(i), value);
    	//error case
    	return '-';

  • 0

    I've copied your code directly and it gave me this error:
    The method getOrDefault(char, int) is undefined for the type HashMap(Character, Integer).

    How should I fix this problem?

  • 0

    Hi, @sooshiant. thank you to ask.
    There's no getOrDefault() function in Java7, so I recommend you check your Java version.
    This method return a value of key(same with get() function) or second parameter if there's no value of the key.
    So if u don't want to update your Java version, You can make this function yourself:)
    Happy coding!

Log in to reply

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