[프로그래머스 lev1/JS] 이상한 문자 만들기

woolee의 기록보관소·2022년 10월 28일
0

알고리즘 문제풀이

목록 보기
28/178

문제 출처

프로그래머스 lev1 - 이상한 문자 만들기

문제

나의 풀이

function solution(s) {
  s=s.split(' ');
  
  for (let i=0; i<s.length; i++) {
    s[i]=s[i].split('');
    for (let j=0; j<s[i].length; j++) {
      if (j%2==0) {
        s[i][j]=s[i][j].toUpperCase()
      }
      else {
        s[i][j]=s[i][j].toLowerCase()
      }
    }
    s[i]=s[i].join('');
  }
  return s.join(' ');
}

console.log(solution("try hello world"));

다른 풀이

O(n) !?

function solution(s) {
  let result = '';
  let num = 0;
  
  for (let i=0; i<s.length; i++) {
    if (s.charAt(i) === ' ') {
      num = 0;
      result += ' ';
      continue;
    }
    else if (num%2===0) {
      result += (s.charAt(i).toUpperCase());
      num++; 
    }
    else {
      result += (s.charAt(i).toLowerCase());
      num++; 
    }
  }
  return result; 
}

console.log(solution("try hello world"));
profile
https://medium.com/@wooleejaan

0개의 댓글