日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

389 find the difference

發布時間:2023/12/10 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 389 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.
 思路:使用hashmap,計算s中每個字符出現的次數。再遍歷字符串t,每遇到一個字符,將map中的值減1。如果字符不出現在map,或者計數為0,就是后來加入的字符。
 

public char findTheDifference(String s, String t) {Map<Character,Integer> map = new HashMap<Character,Integer>();for (int i = 0; i < s.length(); i++) {if(map.get(s.charAt(i))==null){map.put(s.charAt(i), 1);}else{map.put(s.charAt(i), map.get(s.charAt(i))+1);}}for (int i = 0; i < t.length(); i++) {if (!map.keySet().contains(t.charAt(i)) || map.get(t.charAt(i))<=0) {return t.charAt(i);}else{map.put(t.charAt(i), map.get(t.charAt(i))-1);}}return t.charAt(0);}

收獲:1 用異或。a^b^a=b,a^b^b=a,a^b^a^b=0。交換兩個int,不用第三個空間的做法是:a=a^b,b=a^b,a=a^b。

參考資料
1 題目
2 討論

總結

以上是生活随笔為你收集整理的389 find the difference的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。