[boj] 1157. 単語学習(node.js)


サマリ
  • 入力文字列で最も頻度の高い文字を返します.
  • 入力値は大文字と小文字を区別せず、出力値は大文字とする.
  • このときに現れる頻度が同じ文字が複数あるとしたら?返却(63).
  • に答える
    説明する
    const fs = require("fs");
    const filePath = process.platform === "linux" ? "dev/stdin" : "input.txt";
    const stdin = fs.readFileSync(filePath).toString().split("\n");
    
    let cnt = 0;
    const input = () => {
      return stdin[cnt++];
    };
    
    const solution = () => {
      const count = new Array(26);
      count.fill(0);
      input()
        .toLowerCase()
        .split("")
        .map((x) => count[x.charCodeAt() - 97]++);
      let answer = 0;
      const max = Math.max.apply(null, count);
      const originalIdx = count.indexOf(max);
      const lastIdx = count.lastIndexOf(max);
      if (originalIdx == lastIdx) {
        answer = originalIdx;
      } else {
        answer = 63 - 97;
      }
      console.log(String.fromCharCode(answer + 97).toUpperCase());
    };
    
    solution();
    覚えておきたい
  • String.fromCharCode(숫자) : int to str
  • 문자.charCodeAt() : str to int
  • array.fill(0)埋め立て
  • array.indexOf(값)配列インデックスの返却
  • array.lastIndexOf(값)インデックスを並べて検索を開始して戻る
  • String.toLowerCase()String.toUpperCase()文字列全体を大文字小文字に変換
  • くどくど言う
  • javascriptではすでに様々な方法が実現されているので驚きです.効果的に適切な場所で使うことが大切です.