389. Find the Difference

来源:互联网 发布:混沌摆钢铁侠淘宝 编辑:程序博客网 时间:2024/05/22 09:07
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.

解法一

public class Solution {    public char findTheDifference(String s, String t) {        //建一个int【26】数组,小写字母只有26种可能性,索引就是char-'a',而数组值就是字符出现在字符串s中的次数        int[] key=new int[26];        char c='a';        for(int i=0;i<s.length();i++)        {            int num=(s.charAt(i)-'a');            key[num]++;        }        for(int i=0;i<t.length();i++)//如果t的元素出现在s中,在对应位置--;        {            int num=(t.charAt(i)-'a');            key[num]--;            if(key[num]<0)            {                c=t.charAt(i);            }        }        return c;      }}


解法二

由于字符串t只比字符串s多了一个字符,那么直接用t中所有字符值的和减去字符串s中字符值的和即可。

public char findTheDifference(String s, String t) {    int r = 0;    for (int i = 0; i < s.length(); i++) {        r -= (int)s.charAt(i);    }    for (int i = 0; i < t.length(); i++) {        r += (int)t.charAt(i);    }    return (char)r;}


解法三

字符串t只比字符串s多了一个字符,也就是说大部分字符都是相同的。那么,可以使用异或的方式,来找出这个不同的值

public char findTheDifference(String s, String t) {    int r = 0;    for (int i = 0; i < s.length(); i++) {        r ^= s.charAt(i);    }    for (int i = 0; i < t.length(); i++) {        r ^= t.charAt(i);    }    return (char)r;}



0 0
原创粉丝点击