题目
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:s = "abcd"t = "abcde"Output:eExplanation:'e' is the letter that was added.
题意
字符串t由字符串s乱序后加入一个随机字母得到,求这个随机的字母。
思路
直接hash记录每个字符的个数在进行比较。
代码实现
Java
class Solution {public char findTheDifference(String s, String t) {int[] hash = new int[26];for (char c : s.toCharArray()) {hash[c - 'a']++;}for (char c : t.toCharArray()) {hash[c - 'a']--;}int i = 0;while (hash[i] == 0) {i++;}return (char)('a' + i);}}
