[leetcode] 389. Find the Difference
来源:互联网 发布:连续统假设知乎 编辑:程序博客网 时间:2024/06/16 02:06
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:eExplanation:'e' is the letter that was added.
这道题是找字符串中多出的字符,题目难度为Easy。
可以统计字符串s中各字符出现的次数,然后遍历字符串t,逐个比对其中字符,最终单独剩下的字符即是多出的字符。具体代码:
class Solution {public: char findTheDifference(string s, string t) { vector<int> cnt(26, 0); for(auto c:s) ++cnt[c-'a']; for(auto c:t) --cnt[c-'a']; for(int i=0; i<26; ++i) { if(cnt[i]) return 'a' + i; } }};
还可以通过位操作来找多出的字符,任意字符按位异或自己得0,所以把s和t中所有字符逐个按位异或即可得出多出的字符。具体代码:
class Solution {public: char findTheDifference(string s, string t) { char diff = 0; for(auto c:s) diff ^= c; for(auto c:t) diff ^= c; return diff; }};
0 0
- LeetCode : 389. Find the Difference
- Leetcode 389. Find the Difference
- 【leetcode】389. Find the Difference
- Leetcode 389. Find the Difference
- LeetCode 389. Find the Difference
- LeetCode 389. Find the Difference
- [LeetCode]389. Find the Difference
- [LeetCode]--389. Find the Difference
- leetcode 389. Find the Difference
- LeetCode 389. Find the Difference
- LeetCode 389. Find the Difference
- leetcode 389. Find the Difference
- 389.[LeetCode]Find the Difference
- 【LeetCode】 389. Find the Difference
- [LeetCode]389. Find the Difference
- leetcode-389. Find the Difference
- Leetcode 389. Find the Difference
- LeetCode 389. Find the Difference
- HTM白皮书学习笔记(一)
- Set接口的实现类HashSet和TreeSet的区别
- 给初学者的RxJava2.0教程(六)
- 将所有printf输出到内存变量中。printf转string
- unslider图片轮播插件初体验(二)
- [leetcode] 389. Find the Difference
- JSP
- 进程与线程的一个简单解释
- IOS-Archive快速打包
- mapreduce
- SVN版本控制
- Tcp 简单通信例子
- NDK开发-之4-ida工具ndk对so文件静态分析
- Android之性能优化【高级篇】