题目:
In this Kata, you will be given two strings a and b and your task will be to return the characters that are not common in the two strings.
这道题目中,接收两个字符串a和b,目的是返回这两个字符串中不重复的字符。
例子
solve("xyab","xzca") // "ybzc"
solve("xyab","xzca") // "ybzc"
solve("xyabb","xzca") // "ybbzc"
solve("abcd","xyz") // "abcdxyz"
solve("xxx","xzca") // "zca"
解法一:
// 通过两次for循环,用includes()去判断
function solve(a,b){
var result = '';
for(let i=0;i<a.length;i++){
if(!(b.includes(a[i]))) result += a[i]
}
for(let i=0;i<b.length;i++){
if(!(a.includes(b[i]))) result += b[i]
}
return result;
}
解法二:(Best Practices)
// ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。
function solve(a,b) {
let setA = new Set(a);
let setB = new Set(b);
return [...(a+b)].filter(c => setA.has(c) ^ setB.has(c)).join("");
};
解法三:
// 通过将两个字符串合并,再用filter去过滤
function solve(a,b){
return (a+b).split("").filter(c => !a.includes(c) || !b.includes(c)).join("");
};