Use char as int for summation, O(N) time and O(1) space


  • 3
    H
    public char findTheDifference(String s, String t) {
        
        if (s == null || t == null || s.length() + 1 != t.length())
            return (char)0;
        
        int sum = 0;
        int i = 0;
        for (i = 0; i <s.length(); i++)  {
            sum += t.charAt(i);
            sum -= s.charAt(i);
        }
        
        sum += t.charAt(i);
        
        return (char)sum;
        
    }

Log in to reply
 

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