389.查出两个字符串中 不同的字母 Find the Difference

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.Input:

解题思路:用字典存储每个字母的出现次数


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Algorithm;
  6. namespace Solution {
  7. public class Solution {
  8. public char FindTheDifference(string s, string t) {
  9. var d = new Dictionary<char, int>();
  10. foreach (var c in s) {
  11. if (d.ContainsKey(c)) d[c]++;
  12. else d[c] = 1;
  13. }
  14. foreach (var c in t) {
  15. if (d.ContainsKey(c)) d[c]++;
  16. else d[c] = 1;
  17. }
  18. foreach (var i in d.Keys) {
  19. if (d[i] % 2 != 0) {
  20. return i;
  21. }
  22. }
  23. return ' ';
  24. }
  25. }
  26. class Program {
  27. static void Main(string[] args) {
  28. Solution s = new Solution();
  29. var res = s.FindTheDifference("abcdef", "abcde");
  30. Console.WriteLine(res);
  31. }
  32. }
  33. }






posted @ 2017-01-10 23:00  xiejunzhao  阅读(141)  评论(0编辑  收藏  举报