我正在尝试解决这个问题:
让函数
CountingAnagrams接受str参数并确定字符串中存在多少个字谜。
例子:
输入:"aa aa odg dog gdo"?—?输出:2
输入:"a c b c run urn urn"?—?输出:1
我试过这个解决方案,但它没有显示正确的答案。我究竟做错了什么?
const CountingAnagrams = (str) => {
let l = str.length,
c = 0,
c1,
c2;
if (l % 2 == 0) {
c1 = str.slice(0, l / 2).split("");
c2 = str.slice(l / 2).split("");
let l2 = c1.length;
for (let i = 0; i < l2; i++) {
let id = c2.indexOf(c1[i]);
if (id !== -1) {
c2[id] = " ";
}
else {
c += 1;
}
}
}
else {
return "-1";
}
return c;
};
console.log("cars are very cool so are arcs and my os", CountingAnagrams("cars are very cool so are arcs and my os"));
console.log("aa aa odg dog gdo", CountingAnagrams("aa aa odg dog gdo"));
console.log("a c b c run urn urn", CountingAnagrams("a c b c run urn urn"));Run Code Online (Sandbox Code Playgroud)
const CountingAnagrams = (str) => {
// Set() helps to remove all the duplicates
const wordUnique = new Set(str.split(/\s+/)),
wordArray = [
...wordUnique
],
hash = {};
let count = 0;
wordArray.forEach((word) => {
// Key will be the sorted word e.g. cba will become abc
let key = word.split('').sort().join('');
// If there is an anagram they will have the same key so whenever the key is avaialable in the hash count will be updated
if (key in hash) {
count += 1;
}
else {
// true is assigned just for making the key available in the hash
hash[key] = true;
}
});
return count;
};
console.log("cars are very cool so are arcs and my os", CountingAnagrams("cars are very cool so are arcs and my os"));
console.log("aa aa odg dog gdo", CountingAnagrams("aa aa odg dog gdo"));
console.log("a c b c run urn urn", CountingAnagrams("a c b c run urn urn"));Run Code Online (Sandbox Code Playgroud)