String 형인 str 인자에서 중복되지 않은 알파벳으로 이루어진 제일 긴 단어의 길이를 반환해주세요.
예를 들어
str = "abcabcabc"
return은 3=> 'abc' 가 제일 길기 때문
str = "aaaaa"
return은 1
=> 'a' 가 제일 길기 때문str = "sttrg"
return은 3
=> 'trg' 가 제일 길기 때문
arr.forEach()
를 사용한 답안
// str: 텍스트
const getLengthOfStr = (str) => {
const arr = str.split('');
const words = [];
let arr2 = [];
arr.forEach((value) => {
if (!arr2.includes(value)) {
arr2.push(value);
} else {
const newWord = arr2.join('').length;
words.push(newWord);
arr2 = [];
arr2.push(value);
}
});
return Math.max(...words.concat(arr2.join('').length));
// array.concat() - clean code
console.log('concat 1 >>',
[words.concat(arr2.join('').length)].find((ele) => Math.max(...ele))); // [3, 3, 3]
console.log('concat 2 >>', [words.concat(arr2.join('').length)]); // [Array(2)]
return Math.max(...words.concat(arr2.join('').length));
};
console.log(getLengthOfStr('abcabcabc')); // abc
console.log(getLengthOfStr('aaaaa')); // a
console.log(getLengthOfStr('sttrg')); //trg
arr.reduce()
를 사용한 답안.
const getLengthOfStr = (str) => {
let notDuplicateStr = [];
const words = str.split("").reduce((acc = [], curr) => {
if (notDuplicateStr.includes(curr)) {
acc.push(notDuplicateStr.join("").length);
notDuplicateStr = [];
}
notDuplicateStr.push(curr);
return acc;
}, []);
const finalWord = notDuplicateStr;
const result = words.concat(finalWord);
return Math.max(...words.concat(notDuplicateStr.length));
};
console.log(getLengthOfStr('abcabcabc')); // abc
console.log(getLengthOfStr('aaaaa')); // a
console.log(getLengthOfStr('sttrg')); //trg