javascript - 在这个 javascript 字谜问题中,我一直在变得虚假而不是真实
问题描述
嗨,我正在使用 Javascript 来解决一个字谜问题。我在比较放入函数的 2 个字符串中制作的 2 个对象时遇到问题。
如果 2 个字符串具有相同的字母出现相同的次数,则该函数应返回 true。无论字符串中的顺序如何。您也忽略了字母的大小写,为此我将所有字符串都设为小写。这是我的代码:
//example:
//validAnagram('', '') //true
//validAnagram('aaz', 'zza') //false
const validAnagram = (str1, str2) => {
str1 = str1.toLowerCase()
str2 = str2.toLowerCase()
const frequency1 = {}
const frequency2 = {}
//if lengths of string isnt the same automatically make it false
if(str1.length !== str2.length){
return false
}
//putting letters of the strings with their frequencies in the objects
for(let letter of str1){
if(!frequency1[letter]){
frequency1[letter] = 1
}
else {
frequency1[letter]++
}
}
for(let letter of str2){
if(!frequency2[letter]){
frequency2[letter] = 1
}
else {
frequency2[letter]++
}
}
for(let char in frequency1){
if(!(frequency2[char])){
return false
}
else if(frequency2[char] !== frequency1[char]){
console.log(char)
return false
}
else{
return true
}
}
}
解决方案
首先:我从 2 个字符串中搜索了所有唯一字符,然后保存在数组中
第二:我连接2个数组,然后使用set,删除所有重复项(字符)
第三:我循环遍历每个字符并查找该项目的出现:如果匹配或不匹配,或者该字符实际上不存在于任何字符串中,可以在控制台中找到。
const string1 = 'dafdsef dgrg tdyhjTdh drdd@ dgrgrth-grth'
const string2 = '@dafdsef dgrg tdyhjtdh drdd dgrgr;thgrth'
console.log("strings matched : "+test_string(string1 , string2));
function test_string(string1 , string2){
jointArray = [...unique_char(string1.toLowerCase()), ...unique_char(string2.toLowerCase())]
neewarray = [...new Set([...jointArray])]
ok = true;
neewarray.forEach( v=> {
var re = new RegExp(v, 'g');
if(string1.match(re) && string2.match(re) ){
if( string1.match(re).length == string2.match(re).length ) {
console.log(` ${v} => matched in 2 strings`)
}
else{
ok = false;
console.log(` ${v} => not matched in 2 strings`)
}
}
else if(string1.match(re)){
ok = false;
console.log(` ${v} => not avialable in a string1 `)
}
else if(string2.match(re)){
ok = false;
console.log(` ${v} => not avialable in a string2 `)
}
})
return ok;
}
function unique_char(str1){
var str=str1;
var uniq_array=[];
for (var x=0;x < str.length;x++){
if(uniq_array.indexOf(str.charAt(x))==-1){
uniq_array.push(str[x]);
}
}
return uniq_array;
}