LeetCode 389. 找不同

题目链接:https://leetcode-cn.com/problems/find-the-difference/

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

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

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

 

示例:

输入:
s = "abcd"
t = "abcde"

输出:
e

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

 1 class Solution {
 2 public:
 3     char findTheDifference(string s, string t) {
 4         int cnt[26]={0};
 5         int len1=s.length(),len2=t.length();
 6         int i,j;
 7         for(i=0;i<len1;i++){
 8             int tmp=s[i]-'a';
 9             cnt[tmp]++;
10         }
11         for(i=0;i<len2;i++){
12             int tmp=t[i]-'a';
13             cnt[tmp]--;
14         }
15         for(i=0;i<26;i++){
16             if(cnt[i]!=0){
17                 char ch='a'+i;
18                 return ch;
19             }
20         }
21         return t[len2-1];
22     }
23 };

 

posted @ 2020-04-11 00:34  wydxry  阅读(302)  评论(0编辑  收藏  举报
Live2D