프로그래머스 서울에서 김서방 찾기

김금동·2021년 11월 12일
0

알고리즘

목록 보기
7/12

https://programmers.co.kr/learn/courses/30/lessons/12919

내 성도 김이다
난 언제 김서방이 될까

function solution(seoul) {
    const pos = seoul.indexOf("Kim")
    return `김서방은 ${pos}에 있다`
}

배열안에 특정한 값을 찾는 함수 indexOf()를 쓰면 쉽게 풀 수 있는 문제다
참고로 indexOf()는 array뿐만 아니라 string에서도 쓸 수 있다.
indexOf(searchElement, fromIndex)
없으면 -1 리턴한다

function solution(seoul) {
  let pos;
  for (let i=0;i<seoul.length;i++){
      if(seoul[i] === 'Kim'){
          pos = i
          break
      }
  }
  return `김서방은 ${pos}에 있다`
}

for문으로 돌려서 푼 풀이다
시간은 for문이 조금 더 빠른 거 같다

profile
나원래chu해

0개의 댓글