문제
문자열을 입력받아 아이소그램인지 여부를 리턴해야 합니다. 아이소그램(isogram)은 각 알파벳을 한번씩만 이용해서 만든 단어나 문구를 말합니다.
입력
인자 1 : str
- string 타입의 공백이 없는 알파벳 문자열
출력
- boolean 타입을 리턴해야 합니다.
주의 사항
- 빈 문자열을 입력받은 경우, true를 리턴해야 합니다.
- 대소문자는 구별하지 않습니다.
입출력 예시
let output = isIsogram('aba');
console.log(output); // false
output = isIsogram('Dermatoglyphics');
console.log(output); // true
output = isIsogram('moOse');
console.log(output); // false
mine
function isIsogram(str) {
let result = true;
let newStr = str.toUpperCase();
if(newStr.length === 0) return result;
for(let i = 0; i < newStr.length; i++) {
if(newStr.slice(i + 1).includes(newStr[i])) {
return false;
} else {
result = true;
}
}
return result;
}
만약 str = 'abcd'라고 한다면 for 반복문으로 str을 순회시킨다.
index i = 0 일때 기준인 str[i] 는 'a' 이고 비교대상은 'bcd'가 된다.
index i = 1 일때 기준인 str[i]는 'b'이고 비교대상은 'cd'가 된다.
.
index i = 3 일때는 비교가 불필요하다.
reference
function isIsogram(str) {
if (str.length === 0) {
return true;
}
let cache = {};
let strLowered = str.toLowerCase();
for (let i = 0; i < strLowered.length; i++) {
if (cache[strLowered[i]]) {
return false;
}
cache[strLowered[i]] = true;
}
return true;
}
referece 코드는 let cache로 빈 객체를 선언하고
각 문자를 키로 true, fasle를 값으로 대응시켜주었다.
만일 기준이 인데 a라는 문자가 객체 cache 없다고 하면 객체 cache 에는 { a : true } 라고 표시가 된다.
좀 더 알고리즘 다운 코드라고 할 수 있다.
'Algorithm & World Class' 카테고리의 다른 글
(Algorithm) Microsoft Online Assessment Questions (0) | 2022.06.13 |
---|---|
(프로그래머스 LV.2) 방문 길이 구하기 (0) | 2022.04.23 |
[알고리즘] 06_[순열] 새로운 치킨 소스 레시피 (0) | 2021.11.11 |
[알고리즘] 05_[중복순열] 가위바위보 (0) | 2021.11.10 |
고차함수 - 함수 결합시 익명함수로 호출 후 다른 함수 호출시 인자 전달하는 형태 (0) | 2021.10.30 |