leetcode 389. Find the Difference 牛人用异或 或者 求和 解决,很简单。

389. Find the Difference

 
Question Editorial Solution
  My Submissions
  • Total Accepted: 7465
  • Total Submissions: 14609
  • Difficulty: Easy

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.










我的解法:利用hashmap进行记录
public class Solution {
public char findTheDifference(String s, String t){
    Map map=new HashMap();
    for(int i=0;i

牛人解法:
java 用异或:
public char findTheDifference_B(String s, String t) {
	char c = 0;
	for (int i = 0; i < s.length(); ++i) {
		c ^= s.charAt(i);
	}
	for (int i = 0; i < t.length(); ++i) {
		c ^= t.charAt(i);
	}
	return c;
}

或者用求和,c:
char findTheDifference(char* s, char* t) {
    int sum1=0,sum2=0;
    for(;*s;s++)
        sum1+=*s;
    for(;*t;t++)
        sum2+=*t;
    return sum2-sum1;
}





你可能感兴趣的:(leetcode)