找不同
题目形容:给定两个字符串 s 和 t,它们只蕴含小写字母。
字符串 t 由字符串 s 随机重排,而后在随机地位增加一个字母。
请找出在 t 中被增加的字母。
示例阐明请见LeetCode官网。
起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
解法一:二进制运算
异或运算:如果a、b两个值不雷同,则异或后果为1。如果a、b两个值雷同,异或后果为0。 所以如果a、b是2个雷同的数,则异或的后果必定是0。
具体处理过程如下:
- 如果s为null或者空字符串,则间接返回t的首个字符。
- 否则,初始化一个x为0,遍历s和t的每一个字符,顺次和x进行异或运算,因为a和b只有一个字符不雷同,所以最终异或的后果即是增加的那个字母。
public class LeetCode_380 { public static char findTheDifference(String s, String t) { if (s == null || s.length() == 0) { return t.charAt(0); } int x = 0; for (int i = 0; i < s.length(); i++) { x ^= s.charAt(i); x ^= t.charAt(i); } x ^= t.charAt(t.length() - 1); return (char) x; } public static void main(String[] args) { System.out.println(findTheDifference("abcd", "abcde")); }}
【每日寄语】 明天的问题是昨天的汗水,今天的胜利还须明天的致力。