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

정재성·2022년 5월 13일
0
post-thumbnail

String 형인 str 인자에서 중복되지 않은 알파벳으로 이루어진 제일 긴 단어의 길이를 반환해주세요.
str: 텍스트 return: 중복되지 않은 알파벳 길이 (숫자 반환)
예를 들어, str = "abcabcabc" return 은 3 => 'abc' 가 제일 길기 때문
str = "aaaaa" return 은 1 => 'a' 가 제일 길기 때문
str = "sttrg" return 은 3 => 'trg' 가 제일 길기 때문


const getLengthOfStr = str => {
let Arr=[];
let strLength =0;
  for(let i=0;i<str.length;i++){
    if(Arr.indexOf(str[i]) === -1 ){
      Arr.push(str[i]);
    
      if(strLength < Arr.length){
        strLength = Arr.length;
      }
    
    }else{
     Arr=Arr.slice(Arr.indexOf(str[i])+1);
      Arr.push(str[i]);
   }
  }
  
    return strLength;
  // 아래 코드를 작성해주세요.
}

1.배열을 담을 변수를 지정한다.

2.길이를 담을 0으로 지정한 변수를 지정한다

3.배열에 indexOf를 사용하여 인자로 들어올 스트링의 각 요소와 비교하여
겹치는 요소가 없으면 str[i]를 그대로 .push()로 배열에 담는다

4.그 후에 0으로 지정한 문자열의 길이보다 배열에 담겨진 요소가 더 크다면
두개의 값은 같다.

5 겹치는요소가 주어진다면 slice를 사용하여 str의 요소를 자르고 남은것을 변수에 담는다.

indexOf = Array.prototype.indexOf()

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

var array = [2, 9, 9];
array.indexOf(2);     // 0
array.indexOf(7);     // -1

.push()=Array.prototype.push()

push() 메서드는 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환합니다.

const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

.slice() =Array.prototype.slice()

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


let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
let citrus = fruits.slice(1, 3)

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
profile
기술블로그 / 일상블로그

0개의 댓글