C solution use Alphabet


  • 0
    S

    The function use alphabet to solve it.

    • alphabet [26] -> 'a-z'

    • initial : alphabet [26] = 0

    • then : the character of s string make alphabet [ offset of character] plus 1

    • then : the character of s string make alphabet [ offset of character] minus 1 , but the added character make it below zero .

    • fin : the answer is alphabet[ c ] < 0 , return c .

    char findTheDifference(char* s, char* t) {
        int len_s = strlen(s);
        int len_t = strlen(t);//t > s
        int i;
        int alphabet[26] = {0};
       
        for(i = 0; i < len_s; ++i){
            alphabet[s[i] - 'a']++;
        }
        for(i = 0; i < len_t; ++i){
            alphabet[t[i] - 'a']--;
        }
        for(i = 0; i < 26; ++i){
            if(alphabet[i] < 0) return 'a' + i;
        }
        return 0;//if not, complier cannt pass!
    }
    

    ps : the way also find more added character than one .


Log in to reply
 

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