我正在看problem solution on leetcode,并且有一个聪明的解决方案,它使用Python的map函数将字符串列表转换为相同大小的矩阵,如下所示:
t = map(None, *words)
解释:
地图(无,...)转置“矩阵”,用无填充缺失的点。例如:
["abc", [('a', 'd', 'f'),
"de", => ('b', 'e', None),
"f"] ('c', None, None)]
我想知道我是否可以用 js 要点达成类似的目标
答案 0 :(得分:1)
创建矩阵(长度相等):
solution=array.reduce((solution,el)=>(el.split("").forEach((letter,index)=>(solution[index]=solution[index]||[]).push(letter)),solution),[]);
//if you really need the *undefineds* :
maxlength=array.reduce((length,arr)=>Math.max(length,arr.length),0);
solution.forEach(el=>el.length=maxlength);
http://jsbin.com/nisoderini/edit?console 由于某种原因而留下的解释...
检查数组中的等长数组:
length=array.reduce((length,arr,i)=>!i?arr.length:(length?(arr.length==length?length:false):false),0);
如果数组不是对称矩阵,则长度为假...
检查方阵
square=array.every(arr=>arr.length==array.length);
答案 1 :(得分:0)
我就是这样做的。
function transpose(mat, replacement){
const len = findMaxArr(mat);
const res = [];
// loop through each row...
mat.map(e => {
const currElemArr = e.split('')
if (e.length === len) {
res.push(currElemArr);
} else {
// if current row len is less than max len
// pad it with the replacement variable
const diff = len - e.length;
const currElemArrPadded = currElemArr.concat(createRepArr(replacement, diff));
res.push(currElemArrPadded);
}
});
return res;
}
// create an array of inp of length len
function createRepArr(inp, len) {
const res = [];
for (let i = 0; i < len; i++) {
res.push(inp);
}
return res;
}
// find maximum length array of string in a string array
function findMaxArr(mat) {
let res = 0;
mat.forEach(m => {
if (m.length > res) {
res = m.length;
}
});
return res;
}
const data = ["abc", "de", "f"];
console.log(transpose(data, 0));