Problem
- Write a function that takes a string input, and returns the first character that is not repeated anywhere in the string.
- 문자열의 어디에서도 반복되지 않는 첫 번째 문자를 반환한다.
Solution 01
function firstNonRepeating(str) {
let lower = str.toLowerCase();
for (let i = 0; i < lower.length; i++) {
if (lower.indexOf(lower[i]) === lower.lastIndexOf(lower[i])) {
return str[i];
}
}
return '';
}
firstNonRepeating('a'); // a
firstNonRepeating('stress'); // t
firstNonRepeating('moonmen'); // e
Solution 02
function firstNonRepeating(str) {
let lower = str.toLowerCase();
for (let i = 0; i < lower.length; i++) {
let sliced = lower.slice(0, i) + lower.slice(i + 1);
if (sliced.indexOf(lower[i]) === -1) {
return str[i];
}
}
return '';
}
firstNonRepeating('a'); // a
firstNonRepeating('stress'); // t
firstNonRepeating('moonmen'); // e
Solution 03
function firstNonRepeating(str) {
for (let i in str) {
if (str.match(new RegExp(str[i], 'gi')).length === 1) {
return str[i];
}
}
return '';
}
firstNonRepeating('a'); // a
firstNonRepeating('stress'); // t
firstNonRepeating('moonmen'); // e