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

Posted 厚积_薄发

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 389. Find the Difference 牛人用异或 或者 求和 解决,很简单。相关的知识,希望对你有一定的参考价值。

389. Find the Difference

    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<Character,Integer>();
    for(int i=0;i<s.length();i++)
        if(!map.containsKey(s.charAt(i)))
            map.put(s.charAt(i),1);
        else
            int temp = (int)map.get(s.charAt(i));
            map.put(s.charAt(i),++temp);
        
    
    for(int a=0;a<t.length();a++)
        if(!map.containsKey(t.charAt(a)))
            return t.charAt(a);
        
        else
            int temp = (int)map.get(t.charAt(a));
            temp--;
            if(temp<0)return t.charAt(a);
            map.put(t.charAt(a),temp);
        
    
    return ' ';
    


牛人解法: 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 389. Find the Difference 牛人用异或 或者 求和 解决,很简单。的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 389. Find the Difference

LeetCode_389. Find the Difference

leetcode No389. Find the Difference

leetcode No389. Find the Difference

LeetCode:Find the Difference_389

LeetCode 389. Find the Difference