leetcode【389】找不同
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.
解题思路:最近在联系map和set的用法,所以就使用了map来做,时间复杂度:o(n).
public char findTheDifference(String s, String t) {
Map<Character,Integer> map = new HashMap<>();
for(char c:t.toCharArray()){
map.put(c,map.getOrDefault(c,0)+1);
}
for (char c:s.toCharArray()){
if(map.containsKey(c))
map.put(c,map.get(c)-1);
}
for(char c:t.toCharArray()) {
if (map.get(c).intValue() == 1)
return c;
}
return 0;
}
还没有评论,来说两句吧...