From 6a4947d83da54ab58a39c5295c51f85e3da15921 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Sat, 15 Sep 2018 23:01:38 +0800 Subject: [PATCH] Create 389. Find the Difference.md --- 389. Find the Difference.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 389. Find the Difference.md diff --git a/389. Find the Difference.md b/389. Find the Difference.md new file mode 100644 index 0000000..f7137de --- /dev/null +++ b/389. Find the Difference.md @@ -0,0 +1,22 @@ +# [389. Find the Difference](https://leetcode.com/problems/find-the-difference/description/) +# 思路 +分别记录两个字符串中每个字符的出现次数,最后比较一下字符的出现次数,次数差1对应的字符即所求。 +因为全是小写字母,所以开辟一个大小为26的数组进行计数即可。另外,没必要开辟两个计数数组,用一个数组记录即可,对s中出现的字符进行次数累加,对t中出现的字符进行次数累减。 +最后次数为-1的对应的字母即所求。 +时间复杂度O(n), 空间复杂度O(1) +# C++ +``` +class Solution { +public: + char findTheDifference(string s, string t) { + vectorcount(26, 0); + for(int i = 0; i < s.size(); i++){ + count[s[i] - 'a']++; + count[t[i] - 'a']--; + } + count[t[t.size() - 1] - 'a']--; + for(int i = 0; i < 26; i++) + if(count[i] == -1) return char(i + 'a'); + } +}; +```