389. Find the Difference Add to List(新添字符)
来源:互联网 发布:淘宝网结婚用品 编辑:程序博客网 时间:2024/06/05 00:14
DescriptionSubmissionsSolutions
Total Accepted: 60224
Total Submissions: 117313
Difficulty: Easy
Contributor: LeetCode
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.
以前有个字符串,再给一个新的字符串,看新加的是哪一个
解法1:
class Solution {public: char findTheDifference(string s, string t) { bool hap[26] ={ true}; for (int i = 0; i < t.size(); i++) { hap[t[i] - 'A' - 32]=false; } for (int i = 0; i < s.size(); i++) { hap[s[i] - 'A'-32]=true; } for (int i = 0; i < 26; i++) { if (hap[i] == false) { return char(i + 'A' + 32) ; } } }};//很稳健的超时了,下面是大神的
解法2:
class Solution {public: char findTheDifference(string s, string t) { unordered_map<char, int>a;//当然建立哈希表啊,老哥,char是索引类型,int为元素类型 for (char b : s)//遍历短的字符串 { a[b]++; } for (char b : t) { if( --a[b]<0)//多余的那个自然就多减了 { cout << b;// } } }
解法3://运用按位异或解决: a*a=0;并且符合交换律class Solution {public: char findTheDifference(string s, string t) { char res=0; for(char a:s) { res^=a; } for(char b:t) { res^=b; } return res; }
加减法.............class Solution {public: char findTheDifference(string s, string t) { char res = 0; for (char c : s) res -= c; for (char c : t) res += c; return res; }};
解法4:class Solution {public: char findTheDifference(string s, string t) { return accumulate(begin(s), end(s += t), 0, bit_xor<int>()); }};
参考链接:
http://www.cnblogs.com/grandyang/p/5816418.html
0 0
- 389. Find the Difference Add to List(新添字符)
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference*
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- Js读取check的几种方法
- 历届试题 最大子阵
- iOS 在Unit Testing 里面使用第三方库
- 【Eigen】How to "install" Eigen?
- BestCoder Round #93酱油记
- 389. Find the Difference Add to List(新添字符)
- 在NotePad++中直接运行TCL
- Python 标准库一览
- vb.net 教程 5-12 绘图实例之统计图 2 折线图
- Linux 下搭建 chrome+postman环境
- 3223. HEOI2013 Ede的新背包问题
- 浮点型数据在计算机内存中存储原理
- 4月1日,StringEqualTest,每日20行。
- Java中的LinkedList