[LeetCode-389]Find the Difference
来源:互联网 发布:小美工作室淘宝真假 编辑:程序博客网 时间:2024/05/22 17:30
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中字符按随机洗牌方式排列后,再在随机的位置加上一个s中没有的字符组成,请找出t中新增的字符。
分析:(cpp)
- 先将两个字符串分别按字符默认顺序排序
- 再循环比较排序后字符串中相同位置的字符是否相同
- 若字符相同,则继续对比下一位
- 若对应位置字符不同,立即结束循环
- 此时t中对应的字符,即为所求,返回即可
class Solution { public: char findTheDifference(string s, string t) { //先将s、t排序(按字母顺序) sort(s.begin(),s.end()); sort(t.begin(),t.end()); int i=0; while( i < t.size() && i < s.size() ) { //在排序后字符串中比较,如果在同一位置,字符相同,则继续比较; if(t[i]==s[i]) i++; //一旦遇到不相同的情况,立即结束循环,返回字符串t中对应位置的字符即可 else break; } return t[i]; } };
分析:(java)
- 采用位运算亦或(^)运算
- 先将c与s中字符依次做亦或运算
- 再将c与t中字符依次做亦或运算
- 等价于将s与t做亦或操作
- 同一个字符经历过两次亦或操作之后,必然为0
- 最终c中字符即为s与t中不同部分
public class Solution { public char findTheDifference(String s, String t) { //定义字符变量c,用于保存最终查找字符 char c=0x00; //先将c与s中字符依次亦或,注意要强制转换类型 for(int i=0;i<s.length();i++) c =(char) (c^s.charAt(i)); //再将c与t中字符依次亦或 //对于同一个字符进行两次亦或操作后,必然为0 for(int j=0;j<t.length();j++) c =(char) (c^t.charAt(j)); //最终c中值即为s与t不同的部分,即为所求 return c; }}
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
- LeetCode.389 Find the Difference
- Leetcode:Find the Difference
- Find the Difference --LeetCode
- LeetCode Find the Difference
- [LeetCode] Find the Difference
- [Leetcode] Find the Difference
- Fragment的使用
- 75.Find Peak Element-寻找峰值(中等题)
- java--servlet相关类(1)
- 多进程和多线程之间的通信方式及通信实现步骤小结
- selinux 基础知识
- [LeetCode-389]Find the Difference
- React(7.2)--React ES6 处理 mixin
- Plus One
- android EventBus
- 网络编程中客户端和服务端通信过程、原理及代码示例
- 图像处理之积分图应用一(半径无关的快速模糊算法)
- RxJava详细解析
- Python 学习第三天
- JAVA基础再回首(二十七)——JAVA中的图形化界面、GUI概述、简单的窗体创建、事件监听机制、动作事件、GUI布局、鼠标事件