884. Uncommon Words from Two Sentences

AC的,分别统计两个字符串的个数,但不是我最初的想法

class Solution {
    public String[] uncommonFromSentences(String A, String B) {
        String[] arr1 = A.split(" ");
        String[] arr2 = B.split(" ");
        Map<String,Integer> map = new HashMap();
        for( String ss : arr1 )
            map.put(ss, map.getOrDefault( ss , 0 ) + 1 );
        for( String ss : arr2 )
            map.put(ss, map.getOrDefault( ss , 0 ) + 1 );  
        
        List<String> res = new LinkedList();
        for( String ss : map.keySet() ){
            if( map.get(ss) == 1 )
                res.add(ss);
        }
        return res.toArray( new String[res.size()]);
    }
}

我最开始的思路是统计每个字符串出现的次数,最后的结果一定是在两个字符串AB中只出现过一次的字符串,这样就可以把AB连接成一个字符串,遍历一遍就可以了,但是我害怕自己实现不了,就没有去尝试一下,但是看了有人和我一样的思路,实现出来并没有想象中那么难,以后要不害怕,就算没写出来也要尝试一下,嗯!

 

还有一种思想是不是统计出现的次数,而是看Map中是否已经有这个KEY了,如果有了就置为2,如果没有,也就是首次出现就置为1,最后检查为1的,这个思想其实就是标识有没有出现,而不在乎出现的次数,更为直接,但是他用到的方法我还不太会。。。

class Solution {
    public String[] uncommonFromSentences(String A, String B) {
        Map<String,Integer> map = new HashMap<>();
        String[] arr1 = A.split(" ");
        String[] arr2 = B.split(" ");
        for( String ss : arr1 ){
            if( map.containsKey( ss ))map.replace( ss , 2 );
            else map.put( ss , 1 );
        }
        for( String ss : arr2 ){
            if( map.containsKey( ss ))map.replace( ss , 2 );
            else map.put( ss , 1 );
        }
        ArrayList<String> ans = new ArrayList<>();
        for( Map.Entry<String,Integer> checker : map.entrySet() ){
            if( checker.getValue() == 1 )ans.add( ( String )checker.getKey() );
        }
        return ans.toArray(new String[0]);
    }
}

尝试着写了一下,还是有很多问题啊。。。学了不少新东西

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值