前几天在做了一道题,这道题的核心问题是数组去重。昨晚之后看到别人的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数组
中且确保不会出现重复字符。代码中的和函数是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中提供的数据结构对字符串(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) } } }
结语
由于这是我人生第一篇博文,用词和语法有不妥的地方,请多多包含。同时,如果文中有错误的地方,请狠狠地吐槽。