leetcode.389 找不同

给定两个字符串 s 和 t,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

示例:

输入:

s = "abcd"

t = "abcde"

输出:

e

解释:

'e' 是那个被添加的字母。

算法思路由男盆友提供,表示感谢~

思路:扫描s,将s中的字符计数顺序放入数组ss中;再扫描t,在ss对应位置中减掉t中字符的计数,某个位置小于0时,该位置输出。

 
char findTheDifference(char* s, char* t) {
    int ss[100]={0};

    int i=0;

    for (i=0;i<strlen(s);i++){
        ss[s[i]-'a']++;
    }
    for ( i=0;i<strlen(t);i++){
        ss[t[i]-'a']--;
        if (ss[t[i]-'a']<0)
            break;
    }
    return t[i];
}
 

猜你喜欢

转载自www.cnblogs.com/fafa23/p/9250929.html
今日推荐