leetcode Find the Difference
阿新 • • 發佈:2018-12-25
Find the Difference
思路:建立兩個map 統計每個字串出現的次數,如果一個字串不包含另一個的字串,返回字元,或者,兩個字元出現的字數不相同,返回字元。
public static void main(String[] args) { String s = "abcd"; String t = "abcde"; char theDifference = findTheDifference(s, t); System.out.println(theDifference); } public static char findTheDifference(String s, String t) { Map<Character, Integer> characterIntegerMap = changeCanConstructChangeMap(s); Map<Character, Integer> characterIntegerMap2 = changeCanConstructChangeMap(t); for(int i=0;i<t.length();i++){ char c = t.charAt(i); if(!characterIntegerMap.containsKey(c)){ return c; }else{ if(!characterIntegerMap.get(c).equals(characterIntegerMap2.get(c))){ return c; } } } return 'a'; } public static Map<Character,Integer> changeCanConstructChangeMap(String ransomNote){ Map<Character,Integer> map=new HashMap<>(); for(int i=0;i<ransomNote.length();i++){ char c = ransomNote.charAt(i); if(map.containsKey(c)){ map.put(c,map.get(c)+1); }else{ map.put(c,1); } } return map; }