Java 7ms solution O(m+n) time, O(1) space


  • 0
    E
    public class Solution {
    
    public char findTheDifference(String s, String t) {
        int lengthS = s.length(); //Can be zero
        int lengthT = t.length(); //Should be lengthS + 1
        if(lengthS == 0) return t.charAt(0);
        
        int sumS = findLetter(s, lengthS); //Smaller
        int sumT = findLetter(t, lengthT); //Larger
        int addedLetterASCII = sumT-sumS;
        return (char) addedLetterASCII;
    }
    
    private int findLetter(String a, int length){
        int sum = 0;
        for(int pos = 0; pos < length; pos++){
            sum += (int) a.charAt(pos);
        }
        return sum;
    }
    }

Log in to reply
 

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