leetcode_389 Find the Difference
来源:互联网 发布:程序员视频教程 编辑:程序博客网 时间:2024/05/29 04:25
题目分析
给定两个字符串s和t,都只包含小写字母,字符串t是由字符串s打乱顺序且在额外的随机位置上添加一个字符组成,请找出这个字符。
解题思路
1)利用一个数组,先统计s字符串中每个字符出现的次数,然后统计t字符串中的次数,最后找出差异的字符串即可。
2)可以利用hash_map来进行统计实现。实现程序
// 方法1 利用数组实现char findTheDifference(string s, string t){ vector<int> count(26, 0); for (int i = 0; i < s.length(); i++) { count[s[i] - 'a']++; } for (int j = 0; j < t.length(); j++) { count[t[j] - 'a']--; } for (int i = 0; i < count.size(); i++) { if (count[i] == - 1) return i + 'a'; } return 'z';}// 方法2:利用hash_map实现(但在提交过程中编译错误,hash_map为定义)char findTheDifference(string s, string t){ hash_map<char, int> mp; for (int i = 0; i < s.length(); i++) { if (mp.find(s[i]) != mp.end()) mp[s[i]]++; else mp.insert(make_pair(s[i], 1)); } for (int i = 0; i < t.length(); i++) { if (mp.find(t[i]) != mp.end()) mp[t[i]]--; else mp.insert(make_pair(t[i], 1)); } hash_map<char, int>::iterator it = mp.begin(); while (it != mp.end()) { if (it->second == 1) return it->first; it++; } return 'z';}
0 0
- leetcode_389 Find the Difference
- LeetCode_389-Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- Find the Difference
- 160.Find the Difference
- LeetCode389. Find the Difference
- Find the Difference
- 389. Find the Difference
- Leetcode:Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- Find the Difference --LeetCode
- [389]Find the Difference
- 389. Find the Difference
- LeetCode Find the Difference
- 登录注册页面的框架(一)
- MySQL查询语句执行的过程
- POJ 2531 - Network Saboteur
- LeetCode(383)Ransom Note
- 【BZOJ2844】albus就是要第一个出场,线性基
- leetcode_389 Find the Difference
- Opencv中的Mat类使用方法总结
- 建议8: 避免给枚举类型的元素提供显式的值
- 质数筛选--快速筛选出小于等于N的质数
- Android0828(二)
- 使用springmvc拦截器进行登录控制
- Java环境变量配置
- struct在C和C++中的区别
- 文章标题