LeetCode-Find the Difference
阿新 • • 發佈:2018-12-18
Description: 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.
題意:給定兩個字串s和t,其中字串t是由s中的所有字元隨機組合後再新增一個隨機字元再任意位置形成的,現在要求找出字串t中新增的這個隨機字元;
解法:由題意我們知道字串s和t僅僅相差了一個字元,因此我們可以用雜湊表分別儲存字串s和t中每個字元出現的次數,之後我們遍歷字串t中的所有鍵(即t中的不同字元),找出與字串s中相應字元次數不相同的那個,就是隨機新增的字元;
Java
class Solution { public char findTheDifference(String s, String t) { Map<Character, Integer> cntS = new HashMap<>(); Map<Character, Integer> cntT = new HashMap<>(); char result = ' '; for (int i = 0; i < t.length(); i++) { if (i < s.length()) { cntS.put(s.charAt(i), cntS.getOrDefault(s.charAt(i), 0) + 1); } cntT.put(t.charAt(i), cntT.getOrDefault(t.charAt(i), 0) + 1); } for (Character key : cntT.keySet()) { if (cntT.get(key) != cntS.getOrDefault(key, 0)) { result = key; break; } } return result; } }