题目

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:

  1. Input:
  2. s = "abcd"
  3. t = "abcde"
  4. Output:
  5. e
  6. Explanation:
  7. 'e' is the letter that was added.

题意

字符串t由字符串s乱序后加入一个随机字母得到,求这个随机的字母。

思路

直接hash记录每个字符的个数在进行比较。


代码实现

Java

  1. class Solution {
  2. public char findTheDifference(String s, String t) {
  3. int[] hash = new int[26];
  4. for (char c : s.toCharArray()) {
  5. hash[c - 'a']++;
  6. }
  7. for (char c : t.toCharArray()) {
  8. hash[c - 'a']--;
  9. }
  10. int i = 0;
  11. while (hash[i] == 0) {
  12. i++;
  13. }
  14. return (char)('a' + i);
  15. }
  16. }