0
点赞
收藏
分享

微信扫一扫

884. 两句话中的不常见单词 / 1544. 整理字符串 / 1512. 好数对的数目

Villagers 2022-01-31 阅读 31
leetcodejava

884. 两句话中的不常见单词【简单题】【每日一题】

思路:【哈希表模拟】

代码:

class Solution {
    public String[] uncommonFromSentences(String s1, String s2) {
        Map<String,Integer> map1 = new HashMap<>();
        Map<String,Integer> map2 = new HashMap<>();
        for (String str : s1.split(" ")){
            if (!map1.containsKey(str)){
                map1.put(str,1);
            }else {
                map1.put(str,map1.get(str)+1);
            }
        }
        for (String str : s2.split(" ")){
            if (!map2.containsKey(str)){
                map2.put(str,1);
            }else {
                map2.put(str,map2.get(str)-1);
            }
        }
        List<String> list = new ArrayList<>();
        for (String key : map1.keySet()){
            if (map1.get(key) == 1 && !map2.containsKey(key)){
                list.add(key);
            }
        }
        for (String key : map2.keySet()){
            if (map2.get(key) == 1 && !map1.containsKey(key)){
                list.add(key);
            }
        }
        return list.toArray(new String[0]);
    }
}

1544. 整理字符串

思路:

代码:

class Solution {
    public String makeGood(String s) {
        StringBuilder sb = new StringBuilder(s);
        int i = 0;
        while (i<sb.length()-1){
            int cha = sb.charAt(i)-sb.charAt(i+1);
            if (Math.abs(cha) == 32){
                sb.deleteCharAt(i);
                sb.deleteCharAt(i);
                i = i > 0 ? i-1 : i;
            }else {
                i++;
            }
        }
        return sb.toString();
    }
}

1512. 好数对的数目

思路:

代码:

class Solution {
    public int numIdenticalPairs(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();
        int ans = 0;
        for (int n : nums){
           if (!map.containsKey(n)){
               map.put(n,1);
           }else {
               map.put(n,map.get(n)+1);
           }
        }
        for (Integer value : map.values()){
            ans += value*(value-1)/2;
        }
        return ans;
    }
}

tip:

临近过年,还是挺忙的,鸽了2天。今天还被冲到家里做核酸,emmm俺都从杭州回家半个月了,一脸懵逼,还得全家都得做,还得全家单检核酸,这是土匪吧~烦死

举报

相关推荐

0 条评论