두 개의 문자열을 인수로 받아 순서와 대소문자에 관계없이 동일한 문자를 포함하는지 확인하는 isEqual()과 같은 함수를 작성해야 합니다.
예를 들어 -
const first = 'Aavsg'; const second = 'VSAAg'; isEqual(first, second); //true
방법:1 배열 사용
이 방법에서는 문자열을 배열로 변환하고 Array.prototype.sort() 메서드를 사용하여 문자열로 다시 변환하고 동일한지 확인합니다.
이에 대한 코드는 -
예시
const first = 'Aavsg';
const second = 'VSAAg';
const stringSort = function(){
return this.split("").sort().join("");
}
String.prototype.sort = stringSort;
const isEqual = (first, second) => first.toLowerCase().sort() ===
second.toLowerCase().sort();
console.log(isEqual(first, second)); 방법 2:지도 사용
이 방법에서는 두 문자열을 동시에 반복하고 다음과 같은 값을 사용하여 amap에 문자 빈도를 저장합니다. -
-1, if it appears in the first string, +1, if it appears in the second string,
마지막으로 모든 키의 합이 0이면 문자열이 동일하지 않고 동일하지 않다는 결론을 내립니다.
이에 대한 코드는 -
예시
const first = 'Aavsg';
const second = 'VSAAg';
const isEqual = (first, second) => {
if(first.length !== second.length){
return false;
}
first = first.toLowerCase();
second = second.toLowerCase();
const map = {};
for(ind in first){
if(map[first[ind]]){
map[first[ind]]++;
}else{
map[first[ind]] = 1;
}
if(map[second[ind]]){
map[second[ind]]--;
}else{
map[second[ind]] = -1;
}
};
return Object.values(map).reduce((acc, val) => val === 0 && acc, true);
};
console.log(isEqual(first, second)); 출력
둘 다에 대한 콘솔의 출력은 -
true