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]);
    }
}

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

猜你喜欢

转载自blog.csdn.net/weixin_40801853/article/details/82079053
今日推荐