头几天在codewars做了一道题,这道题的中心问题是数组去重。昨晚以后看到他人的solution,觉得本身的solution太low了。
问题
Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters, – each taken only once – coming from s1 or s2.
有两个字符串s1和s2,值只能为a-z。现写一函数,返回一个新的升序的字符串,其值由s1、s2中的值构成,请求包括最多字符且不能反复。
比方:
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"
a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"
My Solution
先贴本身的代码。
我的计划是经由过程一个新数组存储字符串,函数getDistinct
担任将s1、s2中的字符保存到target数组
中且确保不会涌现反复字符。
代码中的Array.from
和includes
函数是ES6中的数组要领。
function longest(s1, s2) {
let distStr,
value,
distArr = []
getDistinct(distArr, s1 + s2)
// 数组排序并转成字符串
distStr = distArr.sort().join('')
return distStr
}
// 数组去重
function getDistinct(target, source) {
let value
// 将字符串转成数组
source = Array.from(source)
for(value of source) {
// 假如target数组中没有该value,则将其增加到数组中
if(!target.includes(value)) {
target.push(value)
}
}
}
Best Solution
这是一切答案中最精巧的一个,仅用了一行就搞定了。(霎时发明差异差异啊)
这个计划起首应用ES6中供应的Set
数据构造对字符串(s1+s2)“去重”,然后构造赋值获得数组,末了举行排序并转成字符串。
const longest = (s1, s2) => [...new Set(s1+s2)].sort().join('')
Other Solution
下面这个计划是我本身计划的ES5版本(不兼容IE8以下的浏览器)
function longest(s1, s2) {
var distStr,
value,
distArr = []
getDistinct(distArr, s1 + s2)
// 数组排序并转成字符串
distStr = distArr.sort().join('')
return distStr
}
// 数组去重
function getDistinct(target, source) {
var index,
value
// 将字符串转成数组
source = Array.prototype.slice.call(source, 0)
for(index in source) {
value = source[index]
// 假如target数组中没有该value,则将其增加到数组中
if(target.indexOf(value) === -1) {
target.push(value)
}
}
}
下面这个计划经由过程新建一个hash对象来纪录已存储的字符。
function longest(s1, s2) {
var distStr,
value,
distArr = []
getDistinct(distArr, s1 + s2)
// 数组排序并转成字符串
distStr = distArr.sort().join('')
return distStr
}
// 数组去重
function getDistinct(target, source) {
var hash = {},
index,
value
// 将字符串转成数组
source = Array.prototype.slice.call(source, 0)
for(index in source) {
value = source[index]
// 假如hash对象中没有该key,则将其增加到数组中
if(!hash[value]) {
target.push(value)
// 给hash增加一个value属性,值为true
hash[value] = true
}
}
}
另有一种计划是先排序,再比较相邻的两个字符,只要当前字符不等于下一个字符的时刻,才存储当前字符。
function longest(s1, s2) {
var distStr,
value,
distArr = []
getDistinct(distArr, s1 + s2)
// 数组排序并转成字符串
distStr = distArr.join('')
return distStr
}
// 数组去重
function getDistinct(target, source) {
var index,
value
// 将字符串转成数组
source = Array.prototype.slice.call(source, 0)
source = source.sort()
for(index in source) {
value = source[index]
// 假如target数组中没有该value,则将其增加到数组中
if(value !== source[index + 1]) {
target.push(value)
}
}
}
结语
因为这是我人生第一篇博文,用词和语法有不妥的处所,请多多包括。同时,假如文中有毛病的处所,请狠狠地吐槽。