Leetcode 389 Find the Difference

来源:互联网 发布:北京网站快速优化排名 编辑:程序博客网 时间:2024/05/18 13:11

Given two strings s andt which consist of only lowercase letters.

String t is generated by random shuffling strings 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[] a = new int[26];        int[] b = new int[26];        int i;        for(i = 0; i < s.length(); i++)          a[s.charAt(i)-'a']++;        for(i = 0; i < t.length(); i++)          b[t.charAt(i)-'a']++;        for(i = 0; i < 26; i++)        {            if(a[i] != b[i])               break;        }        return (char)(i+'a');    }}
//方法二public class Solution {    public char findTheDifference(String s, String t) {        int charCodeS = 0, charCodeT = 0;        for (int i = 0; i < s.length(); ++i) charCodeS += (int)s.charAt(i);        for (int i = 0; i < t.length(); ++i) charCodeT += (int)t.charAt(i);        return (char)(charCodeT - charCodeS);    }}



0 0