[英]how to return same letters elements with O(n) time complexity in javascript?
I am trying to solve a problem with lower time complexity which in this case O(n)
. 我正在尝试解决时间复杂度较低的问题,在这种情况下为O(n)
。
Here is the problem: 这是问题所在:
let arr = ['dog', 'come', 'ogd', 'something', 'emoc'];
It should return 它应该返回
[['dog', 'ogd], ['come', 'emoc']]; // which same using letters
So far I solved this problem using two functions it is working great but mine is nested loop will give me O(n2)
到目前为止,我已经使用两个函数解决了这个问题,它的效果很好,但是我的嵌套循环会给我O(n2)
Here is my code 这是我的代码
const isSameChars = (str1, str2) => {
let str1sorted = str1.split("").sort().join("");
let str2sorted = str2.split("").sort().join("");
if (str1.length !== str2.length) {
return false;
}
for (var i = 0; i < str1sorted.length; i++) {
let char1 = str1sorted[i];
let char2 = str2sorted[i];
if (char1 !== char2) {
return false;
}
}
return true;
}
const isSameCharElements = (arr) => {
let result = [];
for(var i = 0; i < arr.length; i++) {
for(var j = 0; j < i; j++) {
if (isSameChars(arr[i], arr[j]) === true) {
result.push(arr[j])
}
}
}
return result;
}
console.log(isSameCharElements(['dog', 'come', 'ogd', 'something',
'emoc'])) // [['dog', 'ogd], ['come', 'emoc']]
Is there any way to solve this with O(n)
time complexity? 有什么办法可以解决O(n)
时间复杂性的问题?
Thank you an advance! 谢谢你提前!
You can have a 'bag of letters' representation of any String by sorting the letters: 您可以通过对字母进行排序来对任何字符串使用“字母袋”表示:
function sortLetters(word){
return word.split('').sort().join('');
}
You can then iterate over your input, grouping words that have the same bag of letters representation into an object: 然后,您可以遍历输入,将具有相同字母表示形式的单词分组到一个对象中:
const grouped = arr.reduce(function (m, word) {
var bagRepr = sortLetters(word);
var withSameLetters = m[bagRepr] || [];
withSameLetters.push(word);
m[bagRepr] = withSameLetters;
return m;
}, {});
const result = Object.values(grouped)
.filter(function (arr) {
return arr.length > 1;
});
This is O(n), provided that sortLetters()
is O(1), which is the case if the words lengths are bounded by a constant. 如果sortLetters()
为O(1),则为O(n),如果单词长度受常量限制,则为这种情况。
Disclaimer: note that we're only talking about asymptotic complexity here - this does not mean at all that this approach is the most efficient from a practical standpoint! 免责声明:请注意,我们在这里仅讨论渐近复杂性-但这并不意味着从实际的角度来看这种方法是最有效的!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.