Java Solution using array: 6ms


  • 17
    S

    Hi. There are several methods you can try to solve this. HashMap, Arrays, Bits, etc. Here, we're going to use a simple array of size 26 for alphabets. Then for each character in s, increment the count.

    Then for each character in t, you should decrement the count. Now if at any point, the count goes below 0, then the character isn't present in t

            for (int i = 0; i < 26; i++) alpha[i] = 0;
            for (char c : s.toCharArray())
                alpha[ c - 'a' ]++;
    
            for (char c : t.toCharArray()) {
               //could do decrement first, then check but yeah
                if (--alpha[c - 'a'] < 0)
                    return c;
            }
    
            return 0;

  • 0
    M

    Same method using character array, keep counting each character in the array. Other than the newly added char, every char should occur at even times, we just need to find the odd occurrence char.

    public class Solution {
        public char findTheDifference(String s, String t) {
            char[] arr = new char[26];
            int len = s.length();
            for(int i = 0; i < len; i++){
                int indexS = s.charAt(i) - 'a';
                int indexT = t.charAt(i) - 'a';
                arr[indexS]++;
                arr[indexT]++;
            }
            int lastOfT = t.charAt(len) - 'a';
            arr[lastOfT]++;
            
            char c = ' ';
            for(int i = 0; i < 26; i++){
                if(arr[i] % 2 != 0){
                    c = (char) ( i + 'a');
                }
            }
            return c;
        }
    }
    

  • 0
    N

    @sharks12 awesome! smartest way ever!


  • 0
    R

    the first for loop is not necessary. by default, it will set to 0


Log in to reply
 

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