[JS] 백준 2941번 크로아티아 알파벳

jsg_ko·2021년 11월 25일
0

코테연습

목록 보기
16/21

내풀이

노드 런타임에서는 정답을 잘 출력하는데 코드가 더러워서그런지 역시나 백준 런타임에선 실패가뜬다
뭐가 틀린지 안알려주니 어디서부터 잘못됐는지 알 수가 없다...
ljes=njakljes=njaknljjc=c=dz=ak
이런식으로 크로아티아알파벳의 입력값이 연속되어 입력됐을때 중복을 못잡아서 그런가?

let input = fs.readFileSync(filePath()).toString();
input = input.slice(0,input.length-1)

const croatiaAlphabet = ['c=','c-','dz=','d-','lj','nj','s=','z='];
let count1 = 0;

function inputcheck(input){ // 입력값에 크로아티아 문자열이 있을경우 true를 return하는 함수
  let flag = false;
  for(let i=0; i < croatiaAlphabet.length; i++){
    if(input.includes(croatiaAlphabet[i])){
      flag = true;
    }
  }
  return flag;
}


while(inputcheck(input)){ // 입력값에 크로아티아 문자열이 있을경우 반복
  for(let i=0; i < croatiaAlphabet.length; i++){ // 저장한 크로아티아 단어들의 배열의 길이만큼 돌린다
    if(input.includes(croatiaAlphabet[i])){ 
      if(croatiaAlphabet[i] === 'dz='){ // 'dz=' 의 경우에는 세글자이기때문에 따로 조건을 달아서 핸들링 
        const idx = input.indexOf(croatiaAlphabet[i]) // idx저장
        let changeInput = '';  
        for(let j=0; j < input.length; j++){
          if(!(j===idx || j===idx+1 || j===idx+2)){ // 크로아티아단어가 시작한 idx 부터 세글자이니까 idx, idx + 1, idx + 2 는 문자열에서 뺀다
            changeInput = changeInput + input[j]
          }
        }
        input = changeInput; // 크로아티아 단어를 뺀 input값으로 업데이트
   
      } else {
        const idx = input.indexOf(croatiaAlphabet[i])
        let changeInput = '';
        for(let j=0; j < input.length; j++){
          if(!(j===idx || j===idx+1)){ // 나머지는 다 두글자이다
            changeInput = changeInput + input[j]
          }
        }
        input = changeInput;
      }
      count1 = count1 + 1; // 마치면 크로아티아 단어 수 카운트해준다 
    }
  }
}

count1 = count1 + input.length; // 이제 input에는 알파벳만 남았으니 그냥 length를 더해주면 된다 

//출력
console.log(count1);

구글풀이


let input = fs.readFileSync(filePath()).toString().trim();

let croatia = ["c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="];

function solution(input) {
  for (let alphabet of croatia) {
    input = input.split(alphabet).join("a"); 
    /*
    문자열에도 split 메서드를 사용할 수 있다는걸 몰랐음.
    split메서드를사용하니 중복도 한번에 잡을 수 있고 비워진곳에 join을 이용해 'a' 를 추가(단어수 맞추기), 다시문자열로 
    바꿔준 형식.
    */
  }
  return input.length;
}

console.log(solution(input));
profile
디버깅에서 재미를 추구하면 안되는 걸까

0개의 댓글