LeetCode-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.


翻译:

给定两个只包含小写字母的字符串  s  t 。

字符串 t 由字符串 s 中的字符随机打乱并在任意位置多加入一个字母构成。

找到 t 中多加入的那个字母。

扫描二维码关注公众号,回复: 940714 查看本文章

例子:

输入:
s = "abcd"
t = "abcde"

输出:
e

解释:
'e' is the letter that was added.


思路:

同样用 map 映射来做,但是这次先映射 t 中的字母及出现的次数,然后和 s 中的匹配,最后剩下的就是 t 中多加的字符了。


C++代码(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <string>
#include <map>
using namespace std;

class Solution {
public:
	char findTheDifference(string s, string t) {
		map<char, int> m;
		for (int i = 0; i < t.size(); i++) {
			m[t[i]]++;
		}
		for (int i = 0; i < s.size(); i++) {
			m[s[i]]--;
		}
		for (int i = 0; i < t.size(); i++) {
			if (m[t[i]] > 0)
				return t[i];
		}
		return NULL;
	}
};

int main()
{
	Solution s;
	string str="a";
	string t="aa";
	char result;
	result = s.findTheDifference(str, t);
	cout << result;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tel_annie/article/details/80238803