중복되지 않은 알파벳으로 이루어진 제일 긴 단어의 길이를 반환

길현민·2022년 7월 7일
0

JS코딩테스트

목록 보기
2/7

문제
String 형인 str 인자에서 중복되지 않은 알파벳으로 이루어진 제일 긴 단어의 길이를 반환해주세요.

str: 텍스트 return: 중복되지 않은 알파벳 길이 (숫자 반환)

예를 들어, str = "abcabcabc" return 은 3 => 'abc' 가 제일 길기 때문

str = "aaaaa" return 은 1 => 'a' 가 제일 길기 때문

str = "sttrg" return 은 3 => 'trg' 가 제일 길기 때문

debugger
const getLengthOfStr = str => {
let sliceStr = [];
let lastStrLength = 0;
for (let i = 0; i < str.length; i++) {
if (sliceStr.indexOf(str[i]) === -1) {
sliceStr.push(str[i]);
if (lastStrLength < sliceStr.length) {
lastStrLength = sliceStr.length;
}
} else {
sliceStr = sliceStr = sliceStr.slice(sliceStr.indexOf(str[i]) + 1);
sliceStr.push(str[i]);
}
}
return lastStrLength;
}
//idexOf("찾는글자",어디서부터)
let str = "sttrg";
let sss = "abcabcabc"
let ttt = "aaaaa"
console.log(getLengthOfStr(str));
console.log(getLengthOfStr(sss));
console.log(getLengthOfStr(ttt));

Array.prototype.indexOf()

indexOf() 메서드는 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환합니다.

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
// expected output: -1

Array.prototype.slice()

slice() 메서드는 어떤 배열의 begin부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]
console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

🐔참고문헌

·Mdn indexOf() 검색

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

·Mdn slice() 검색

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

profile
맛집탐방러

0개의 댓글