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

来源:互联网 发布:淘宝代购耐克是正品吗 编辑:程序博客网 时间:2024/06/06 13:01

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:eExplanation:'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;}





0 0
原创粉丝点击