LeetCode - 500. Keyboard Row (JavaScript)

조민수·2024년 7월 4일
0

LeetCode

목록 보기
48/61

Easy, 문자열

RunTime : 47 ms / Memory : 48.69 MB


문제

Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.

In the American keyboard:

the first row consists of the characters "qwertyuiop",
the second row consists of the characters "asdfghjkl", and
the third row consists of the characters "zxcvbnm".


풀이

  • 간단한 문자열 문제
  • forEach를 사용하지 않았다면 tmp를 스택으로 활용해서 [-1]과 비교해서 해결하는 것도 좋을 것 같다.
    • 시간소요가 줄어들 수 있다.
var findWords = function(words) {
    var first = "qwertyuiop";
    var second = "asdfghjkl";
    var last = "zxcvbnm";

    var res = new Array();

    words.forEach((word) => {
        var tmp = new Set();
        word.toLowerCase().split('').forEach((e) => {
            if(first.includes(e)){
                tmp.add(1);
            } else if(second.includes(e)){
                tmp.add(2);
            } else{
                tmp.add(3);
            }
        });
        if(tmp.size === 1){
            res.push(word);
        }
    });
    return res;
};
profile
사람을 좋아하는 Front-End 개발자

0개의 댓글