此博客鏈接:
找不同
題目鏈接:https://leetcode-cn.com/problems/find-the-difference/
題目
給定兩個字符串 s 和 t,它們只包含小寫字母。
字符串 t 由字符串 s 隨機重排,然后在隨機位置添加一個字母。
請找出在 t 中被添加的字母。
示例 1:
輸入:s = "abcd", t = "abcde"
輸出:"e"
解釋:'e' 是那個被添加的字母。
示例 2:
輸入:s = "", t = "y"
輸出:"y"
示例 3:
輸入:s = "a", t = "aa"
輸出:"a"
示例 4:
輸入:s = "ae", t = "aea"
輸出:"a"
題解
使用兩個哈希表,把字符串分別存到兩個哈希表中,判斷哈希表中相同字符的個數是否相同。
不相同則說明多的是不相同的字符。不相同有三種不相同。
1.一個字符串為空,另外一個字符串只含有一個字符,則這個字符就是多的字符。
2.兩個哈希表中的字符是一樣的,但是個數不一樣,則說明這個字符就是多的字符。
3.兩個哈希表中,一個哈希表存在某個字符,另外一個哈希表不存在這個字符,則說明這個字符是多的字符。
代碼
class Solution { public char findTheDifference(String s, String t) { if(s==null) { return t.charAt(0); } Map<String,Integer> map1=new HashMap(); Map<String,Integer> map2=new HashMap(); char reslut='0'; for(int i=0;i<s.length();i++){ Integer count1=map1.get(s.charAt(i)); if(count1==null) { map1.put(s.charAt(i)+"",1); } else map1.put(s.charAt(i)+"",count1++); } for(int i=0;i<t.length();i++){ Integer count2=map2.get(t.charAt(i)); if(count2==null) { map2.put(t.charAt(i)+"",1); } else map2.put(t.charAt(i)+"",count2++); } for(String temp1:map1.keySet()){ for(String temp2:map2.keySet()){ if(map1.get(temp1)==map2.get(temp2)) break; if(map1.get(temp1)<map2.get(temp2)){ reslut=temp1.charAt(0); } if(map1.get(temp2)==null&&map2.get(temp2)!=null) { reslut=temp2.charAt(0); } } } return reslut; } }
結果
但是第一個結果就不對,今天沒有心情,睡覺吧。
修改代碼
以上代碼出現兩個致命問題
問題1 在判斷字母長度時,沒有對是否是相等字符做判斷。
問題2在雙重遍歷哈希表時,外層循環應該是寫字母多的哈希表,內層循環應該寫字母少的哈希表。
正確代碼
class Solution { public char findTheDifference(String s, String t) { if(s.length()==0) { return t.toCharArray()[0]; } Map<Character,Integer> map1=new HashMap(); Map<Character,Integer> map2=new HashMap(); char reslut='0'; for(int i=0;i<s.length();i++){ Integer count1=map1.get(s.charAt(i)); if(count1==null) { map1.put(s.charAt(i),1); } else map1.put(s.charAt(i),++count1); } for(int i=0;i<t.length();i++){ Integer count2=map2.get(t.charAt(i)); if(count2==null) { map2.put(t.charAt(i),1); } else map2.put(t.charAt(i),++count2); } System.out.println(map1); System.out.println(map2); System.out.println(map1.get('e')); System.out.println(map2.get('e')); for(Character temp2:map2.keySet()){ for(Character temp1:map1.keySet()){ if(map1.get(temp1)==map2.get(temp2)&&temp1==temp2) break; if(map1.get(temp1)<map2.get(temp2)&&temp1==temp2){ reslut=temp1; } if(map1.get(temp2)==null&&map2.get(temp2)!=null) { reslut=temp2; } } } return reslut; } }
結果