我想使用node js编程语言来优化下面的程序,任何人都可以帮我。我尝试了给定的代码,但我想优化更多
function anagramsArray() { let arr = ["cab", "cz", "abc", "bca", "zc"]; let result = [] for(let i=0; i<arr.length; i++) { let iSortedValue = sortString(arr[i]) let innerResult = [] innerResult.push(arr[i]) for(let j=i+1; j<arr.length; j++) { let jSortedValue = sortString(arr[j]) if(iSortedValue.length == jSortedValue.length && jSortedValue == jSortedValue) { innerResult.push(arr[j]) arr.splice(j,1) j-- } } result.push(innerResult) } return result } console.log(anagramsArray()) function sortString(reqV) { let reqValue = reqV.split("") for(let i=0; i<reqValue.length; i++) { for(let j=i; j<reqValue.length; j++) { if(reqValue[i] > reqValue[j]) { let temp = reqValue[i] reqValue[i] = reqValue[j] reqValue[j] = temp } } } return reqValue.join("") }
结果:: [[[“ abc”,“ bca”,“ cab”],[“ zc”,cz“]]
答案 0 :(得分:1)
首先,您的sortString
函数可以“简化”为以下内容:
function sortString(str) {
return Array.from(str) // Converts string to array of characters
.sort() // Sorts them
.join(''); // Creates string again
}
实际上,可以以多种方式完成分组字谜的实际逻辑。您已经完成的操作也是有效的,但这是非常“ C”风格的代码。以下是使用可用JS功能的一种方法:
function anagramsArray() {
let arr = ["cab", "cz", "abc", "bca", "zc"];
// Following reduction creates a Map from 'sorted string' to list of
// strings that result in same sorted string. i.e. list of anagrams
const resultObj = arr.reduce((accumulator, str) => {
const sortedStr = sortString(str);
if(!accumulator[sortedStr]) {
accumulator[sortedStr] = [];
}
accumulator[sortedStr].push(str);
return accumulator;
}, {});
// Following mapping discards the keys in object above,
// and returns the Array of arrays that the user expects.
return Object.keys(resultObj).map(key => resultObj[key]);
}