389. Find the Difference的C++解法
2017-03-31 11:05
155 查看
要考虑到统计重复字母的个数,比如s里有3个a,t里面有4个a,所以多出来的是a。我的解决办法就是找到一个删除一个,要使用迭代器。
class Solution {
public:
char findTheDifference(string s, string t) {
int i;
for (i = 0; i < t.length(); i++)
{
int flag = 1;
string::iterator it;
for (it = s.begin(); it != s.end(); ++it)
{
if (*it == t[i])
{
s.erase(it);
flag = 0;
break;
}
}
if (flag==1) return t[i];
}
}
};
看了下最优解发现又忽略了XOR的作用!!!这种只多出一个来的用XOR解决起来超级简单啊!!我是真的傻!!!
最优解算法:
class Solution {
public:
char findTheDifference(string s, string t) {
char r=0;
for(char c:s) r ^=c;
for(char c:t) r ^=c;
return r;
}
};
class Solution {
public:
char findTheDifference(string s, string t) {
int i;
for (i = 0; i < t.length(); i++)
{
int flag = 1;
string::iterator it;
for (it = s.begin(); it != s.end(); ++it)
{
if (*it == t[i])
{
s.erase(it);
flag = 0;
break;
}
}
if (flag==1) return t[i];
}
}
};
看了下最优解发现又忽略了XOR的作用!!!这种只多出一个来的用XOR解决起来超级简单啊!!我是真的傻!!!
最优解算法:
class Solution {
public:
char findTheDifference(string s, string t) {
char r=0;
for(char c:s) r ^=c;
for(char c:t) r ^=c;
return r;
}
};
相关文章推荐
- leetcode之389. Find the Difference(C++解法)
- LeetCode - 389. Find the Difference - 三种不同解法 - ( C++ ) - 解题报告
- 【LeetCode-389】Find the Difference(C++)
- LeetCode 389. Find the Difference 题解(C++)
- leetcode 389 Find the Difference C++
- 389. Find the Difference
- 389. Find the Difference
- [389]Find the Difference
- Leetcode 389. Find the Difference 找不同 解题报告
- 389. Find the Difference
- leetcode 389. Find the Difference 牛人用异或 或者 求和 解决,很简单。
- LeetCode389. Find the Difference简单
- 389. Find the Difference
- Leetcode 389 Find the Difference
- Leetcode 389. Find the Difference
- 389. Find the Difference [easy] (Python)
- [leetcode] 389. Find the Difference 解题报告
- LeetCode389. Find the Difference
- LeetCode 389 Find the Difference
- LeetCode(389) Find the Difference