389. Find the Difference

Posted andywu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
‘e‘ is the letter that was added.

题目含义:给定两个字符串s和t,都只包含小写字母,字符串t是由字符串s打乱顺序且在额外的随机位置上添加一个字符组成,请找出这个字符

方法一:

 1     public char findTheDifference(String s, String t) {
 2         char result = 0;
 3         for (int i=0;i<t.length();i++){
 4             result += t.charAt(i);
 5         }
 6 
 7         for (int i=0;i<s.length();i++){
 8             result -= s.charAt(i);
 9         }
10         return result;  
11     }

方法二:

 1     public char findTheDifference(String s, String t) {
 2         char result = 0;
 3         for (int i=0;i<s.length();i++){
 4             result ^= s.charAt(i);
 5         }
 6 
 7         for (int i=0;i<t.length();i++){
 8             result ^= t.charAt(i);
 9         }
10         return result;
11     }

 

以上是关于389. Find the Difference的主要内容,如果未能解决你的问题,请参考以下文章

389. Find the Difference

389. Find the Difference

389. Find the Difference

LeetCode 389. Find the Difference

Leetcode 389 Find the difference

LeetCode 389. Find the Difference