String 형인 str 인자에서 중복되지 않은 알파벳으로 이루어진 제일 긴 단어의 길이를 반환해주세요.
str: 텍스트 return: 중복되지 않은 알파벳 길이 (숫자 반환)
예를 들어, str = "abcabcabc" return 은 3 => 'abc' 가 제일 길기 때문
str = "aaaaa" return 은 1 => 'a' 가 제일 길기 때문
str = "sttrg" return 은 3 => 'trg' 가 제일 길기 때문
하나의 문자열을 입력 받아서 그 문자열 중에 중복이 없고, 연속적으로 가장 긴 단어의 길이를 반환하해라
str.split('').reduce((acc, currentValue) => {}, []);
왜 초기화 시켜주지?
라는 의문이 들수있다. 그러면 문제를 한 번더 보고오면 이해할 수 있다.if (notOverlap.includes(currentValue)) {
acc.push(notOverlap.join('').length);
notOverlap = [];
}
Math.max(...maxLengthArr, notOverlap.length);
const getLengthOfStr = str => {
let notOverlap = [];
const maxLengthArr = str.split('').reduce((acc, currentValue) => {
if (notOverlap.includes(currentValue)) {
acc.push(notOverlap.join('').length);
notOverlap = [];
}
notOverlap.push(currentValue);
return acc;
}, []);
return Math.max(...maxLengthArr, notOverlap.length);
};
console.log(getLengthOfStr('abcabcabc'));
console.log(getLengthOfStr('aaaaa'));
console.log(getLengthOfStr('sttrg'));
그동안 잘 사용해보지 못했던 reduce에 대해서 조금 더 이해하게된 계기를 얻은거 같다.