力扣 389. 找不同 难度:简单

题目

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

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

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

 

示例 1:

输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。
示例 2:

输入:s = "", t = "y"
输出:"y"
示例 3:

输入:s = "a", t = "aa"
输出:"a"
示例 4:

输入:s = "ae", t = "aea"
输出:"a"

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-difference


题解

这道题可以使用计数法,先把s的字符技术,然后对t的字符数进行比较.

s.charAt(i) : 取i位置的字符

 

代码

 

 1   public char findTheDifference(String s, String t) {
 2         int[] cnt = new int[26];
 3         for (int i = 0; i < s.length(); ++i) {
 4             char ch = s.charAt(i);
 5             cnt[ch - 'a']++;
 6         }
 7         for (int i = 0; i < t.length(); ++i) {
 8             char ch = t.charAt(i);
 9             cnt[ch - 'a']--;
10             if (cnt[ch - 'a'] < 0) {
11                 return ch;
12             }
13         }
14         return ' ';
15     }

 

posted @ 2022-01-20 16:52  宗神一  阅读(24)  评论(0编辑  收藏  举报