[LeetCode]389. Find the Difference(找不同)
来源:互联网 发布:matlab数据归一化 编辑:程序博客网 时间:2024/05/21 10:04
389. Find the Difference
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.
题目大意:
给定两个只由小写字母组成的字符串s和t。
字符串t由字符串s 随机洗牌(打乱顺序) 生成,然后在随机位置添加一个字母。
找到在t中添加的字母。
Example:
Input:s = "abcd"t = "abcde"Output:eExplanation:'e' is the letter that was added.
思路:遍历两个字符串,将t中与s相同的字符统统赋值为’0’,剩下的一个未被赋值的字符即为要找的字母
代码如下:
C++#include <iostream>#include <string>using namespace std;class Solution {public: char findTheDifference(string s, string t) { int s_length = s.length(); int t_length = t.length(); for(int i=0;i<s_length;i++)//遍历字符串s { for(int j=0;j<t_length;j++)//遍历字符串t { if(s[i] == t[j])//若在字符串t中 找到与 字符串s中元素 相同的字符 { t[j] = '0';//将t中该元素赋值'0' break;//并结束遍历字符串t } } } for(int m=0;m<t_length;m++)//遍历字符串t { if(t[m] != '0')//找到没有被赋值为'0'的元素 返回该值 return t[m]; } return t[s_length]; }};int main(){ Solution a; cout << a.findTheDifference("aa", "aea") << endl; return 0;}
注意:
- 将t中元素重新赋值后一定要结束遍历t,并进行遍历下一个s中元素。否则会把t中相同元素全部赋值为’0’
- 例如:s = “ae”; t = “aae”; 遍历s中的a时,就会把t中所有的a全部赋值’0’,最后结果得不到正确值
- break;结束当前for循环(遍历t的循环)但不会结束外层for循环(遍历s的循环)
- 该方法思路简单但是时间复杂度比较大
- http://blog.csdn.net/qq508618087/article/details/52352635查看其它博客,有用异或方法
- http://www.cnblogs.com/qinduanyinghua/p/5827777.html 用Hash表方法
- http://blog.csdn.net/Xiejingfa/article/details/50469045【C++11新特性】 auto关键字
0 0
- [LeetCode]389. Find the Difference(找不同)
- Leetcode 389. Find the Difference 找不同 解题报告
- 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
- leetcode 389. Find the Difference
- 389.[LeetCode]Find the Difference
- 【LeetCode】 389. Find the Difference
- [LeetCode]389. Find the Difference
- 继承System.Web.UI.Page的页面基类
- 初探Linux——Linux中常用的操作命令
- 如何在微信小程序中实现今日头条App那样的Topbar
- BIO
- getParameterValues和getParameter的区别
- [LeetCode]389. Find the Difference(找不同)
- react native开发:实现点击左侧选择项,右侧显示内容的功能
- java.lang.ClassNotFoundException: com.fasterxml.jackson.core.JsonProcessingException
- 纯css实现进度条效果
- future.channel().closeFuture().sync();后面代码不执行
- 盒模型代码简写
- Mysql limit 分页机制和优化实例
- 你什么都没错,只是太老了。
- Json对象与Json字符串互转(4种转换方式)