20240726 알고리즘 코드 카타

RingKim1·2024년 7월 26일

algorithm

목록 보기
18/18

풀이

function solution(my_string, k) {
    let answer = '';
    while(k > 0) {answer += my_string; k--;}
    return answer;
}
function solution(str_list) {
    let answer = [];
    
    const indexL = str_list.indexOf("l");
    const indexR = str_list.indexOf("r");

    // "l"이 먼저 나오거나 존재하지 않을 때
    if (indexL !== -1 && (indexR === -1 || indexL < indexR)) {
        answer = str_list.slice(0, indexL);
    } 
    // "r"이 먼저 나오거나 존재하지 않을 때
    else if (indexR !== -1) {
        answer = str_list.slice(indexR + 1);
    }

    return answer;
}

그냥 막상 풀었을 때 쉽다고 여겼는데 조건 처리 하는게 길어져서 귀찮았다..

function solution(arr) {
    for(let i = 0; i < arr.length; i++) {
        if (arr[i] === 'l') return arr.slice(0, i);
        if (arr[i] === 'r') return arr.slice(i + 1);
    }
    return [];
}

역시 다른 사람들이 푼것은 깔끔..


정리

  • while(){} 는 ()안이 true 일 경우에만 실행
  • indexOf()는 값이 있으면 해당 index 값을 없다면 -1을 리턴!
profile
커피는 콜드브루

0개의 댓글