Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

884.两句话中的不常见单词 #19

Open
funnycoderstar opened this issue Sep 12, 2018 · 0 comments
Open

884.两句话中的不常见单词 #19

funnycoderstar opened this issue Sep 12, 2018 · 0 comments

Comments

@funnycoderstar
Copy link
Owner

funnycoderstar commented Sep 12, 2018

JavaScript实现LeetCode第884题:两句话中的不常见单词

题目描述

给定两个句子 A 和 B 。(句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)

如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的。

返回所有不常用单词的列表。

您可以按任何顺序返回列表。

示例 1:

输入:A = "this apple is sweet", B = "this apple is sour"
输出:["sweet","sour"]

示例 2:

输入:A = "apple apple", B = "banana"
输出:["banana"]

思路分析

仔细分析一下其实就是, 先把这两个参数转换成数组, 把这两个数组合并, 找出只出现一次的元素.

思路一:

遍历转换后的数组A和数组,找出只出现一次的元素

思路二:

将两个数组合并,新建一个Map, 里面的key是当前元素, value为出现的次数, 最后统计次数为1的元素

解决方法

方法一

/**
 * @param {string} A
 * @param {string} B
 * @return {string[]}
 */
function checkout(paramA, arrB, A) {
    let arrA = paramA.concat();
    let result = [];
    for(let i = 0; i < arrA.length; i++) {
        let a = arrA[i];
        arrA.splice(i, 1);
        if(!arrA.includes(a) && !arrB.includes(a) ) {
            result.push(a);
        }
        arrA = paramA.concat();
    }
    return result;
}
var uncommonFromSentences = function(A, B) {
    let arrA = A.split(' ');
    let arrB = B.split(' ');
    return checkout(arrA, arrB, A).concat(checkout(arrB, arrA, B));
};

方法二

var uncommonFromSentences = function(A, B) {
    let map = new Map();
    A.split(' ').concat(B.split(' ')).forEach(item => {
        if(map.has(item)) {
            map.set(item, map.get(item) + 1);
        } else {
            map.set(item, 1);
        }
    });
    let result = [];
    map.forEach((value, key, map) => {
        if(value == 1) {
            result.push(key);
        }
    })
    return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant