*389. Find the Difference (string + map(26)) read problems carefully

Posted stiles

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了*389. Find the Difference (string + map(26)) read problems carefully相关的知识,希望对你有一定的参考价值。

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.

 

class Solution {
    public char findTheDifference(String s, String t) {
        //in the middle(start) or  in the end
        //get small length
        int sn = s.length();
        int tn = t.length();
        if(sn > tn)
        return helper(s,t);
        else return helper(t,s);
    }
    char helper(String l, String s){ // larger and smaller
        int[] a = new int[26];
        int[] b = new int[26];
        for(int i = 0; i<l.length(); i++){
            a[l.charAt(i) - ‘a‘] ++;
        }
        for(int i = 0; i<s.length(); i++){
            b[s.charAt(i) - ‘a‘] ++;
        }
        for(int i = 0; i<26; i++){
            if(a[i] != b[i]) return (char)(i+‘a‘);
        }
        return ‘a‘;
    }
}

 

以上是关于*389. Find the Difference (string + map(26)) read problems carefully的主要内容,如果未能解决你的问题,请参考以下文章

389. Find the Difference

389. Find the Difference

389. Find the Difference

LeetCode 389. Find the Difference

Leetcode 389 Find the difference

LeetCode 389. Find the Difference