挑战:
把一个字符串中的字符重新排列生成新的字符串,返回新生成的字符串里没有连续重复字符的字符串个数.连续重复只以单个字符为准
例如, aab 应该返回 2 因为它总共有6中排列 (aab, aab, aba, aba, baa, baa), 但是只有两个 (aba aba)没有连续重复的字符 (在本例中是 a).
举例:
permAlone("aab") 应该返回一个数字.
permAlone("aab") 应该返回 2.
permAlone("aaa") 应该返回 0.
permAlone("aabb") 应该返回 8.
permAlone("abcdefa") 应该返回 3600.
permAlone("abfdefa") 应该返回 2640.
permAlone("zzzzzzzz") 应该返回 0.
答案:
方法 | |
---|---|
=> | ES6标准新增了一种新的函数:Arrow Function(箭头函数)。 |
let | 作用是声明变量,和var差不多。 |
slice() | 从某个已有的数组返回选定的元素 |
concat() | 用于连接两个或多个数组。 |
var permAlone=(() => {
var count; //计数器
function judge(arr) { //判断是否符合要求
for(let i=0,l=arr.length;i<l-1;i++){
if( arr[i]==arr[i+1] ){
return;
}
}
count++;
}
function fn(source, result) {
if (source.length === 0){
judge(result);
}else{
for (var i = 0; i < source.length; i++){
fn(source.slice(0, i).concat(source.slice(i + 1)), result.concat(source[i]));
}
}
}
return str => {
var arr=str.split("");
count=0;
fn(arr, []);
return count;
};
})();
permAlone('aab');
运行结果:
2
在线测试: