Fork me on GitHub

[leetcode-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.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.

思路:

用一个map统计s里的字符情况,然后遍历t,将map里对应的字符的出现次数-1。如果没有在map里说明就是要找的字符。

如果有重复的字符,则会出现负数情况,遍历即可。思路很简单,就是费空间,待优化。

char findTheDifference(string s, string t)
     {
         map<char, int>str;
         for (int i = 0; i < s.size();i++)
         {
             str[s[i]]++;
         }
         for (int i = 0; i < t.size();i++)
         {
             if (str.count(t[i])) str[t[i]]--;             
             else return t[i];
         }
         map<char, int>::iterator it;
         for (it = str.begin(); it != str.end();it++)
         {
             if (it->second < 0) return it->first;
         }
     }

 

posted @ 2017-05-12 21:10  hellowOOOrld  阅读(163)  评论(0编辑  收藏  举报