leetcode_389 Find the Difference

来源:互联网 发布:程序员视频教程 编辑:程序博客网 时间:2024/05/29 04:25
  • 题目分析

    给定两个字符串s和t,都只包含小写字母,字符串t是由字符串s打乱顺序且在额外的随机位置上添加一个字符组成,请找出这个字符。

  • 解题思路

    1)利用一个数组,先统计s字符串中每个字符出现的次数,然后统计t字符串中的次数,最后找出差异的字符串即可。
    2)可以利用hash_map来进行统计实现。

  • 实现程序

// 方法1 利用数组实现char findTheDifference(string s, string t){    vector<int> count(26, 0);    for (int i = 0; i < s.length(); i++)    {        count[s[i] - 'a']++;    }    for (int j = 0; j < t.length(); j++)    {        count[t[j] - 'a']--;    }    for (int i = 0; i < count.size(); i++)    {        if (count[i] == - 1)            return i + 'a';    }    return 'z';}// 方法2:利用hash_map实现(但在提交过程中编译错误,hash_map为定义)char findTheDifference(string s, string t){    hash_map<char, int> mp;    for (int i = 0; i < s.length(); i++)    {        if (mp.find(s[i]) != mp.end())            mp[s[i]]++;        else            mp.insert(make_pair(s[i], 1));    }    for (int i = 0; i < t.length(); i++)    {        if (mp.find(t[i]) != mp.end())            mp[t[i]]--;        else            mp.insert(make_pair(t[i], 1));    }    hash_map<char, int>::iterator it = mp.begin();    while (it != mp.end())    {        if (it->second == 1)            return it->first;        it++;    }    return 'z';}
0 0
原创粉丝点击