IncredibleThings

导航

LeetCode-Find the Difference

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) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for(int i=0; i<s.length(); i++){
            char c = s.charAt(i);
            if(map.containsKey(c)){
                map.put(c,map.get(c)+1);
            }
            else{
                map.put(c,1);
            }
        }
        
        for(int i=0; i<t.length(); i++){
            char c= t.charAt(i);
            if(!map.containsKey(c)){
                return c;
            }
            else{
                int v = map.get(c);
                if (v == 0){
                    return c;
                }
                else{
                    map.put(c, v-1);
                }
            }
        }
        
        return ' ';
    }
}

 

posted on 2017-12-13 10:41  IncredibleThings  阅读(127)  评论(0编辑  收藏  举报