본문 바로가기

Algorithm/Brute Force

(C++) - LeetCode (easy) 500. Keyboard Row

반응형

https://leetcode.com/problems/keyboard-row/description/

 

Keyboard Row - LeetCode

Can you solve this real interview question? Keyboard Row - 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 ro

leetcode.com

전수조사 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 첫 째, 둘 째, 셋 째 행의 keyboard의 자판을 각각 변수 first ~ thirdRow를 선언해 저장해줍니다.2. 정답을 반환할 vector ans를 선언해줍니다.

📔 풀이과정

words에 대해 for loop를 수행합니다.

1. 지역변수 canFirst, canSecond, canThird를 선언해 줍니다. 이는 x번째 행에 몇 개의 문자를 입력할 수 있는지에 대한 값이 저장됩니다.

2. 하나의 문자열 w에 대해 for loop를 수행하며 매번 한 문자를 소문자로 치환한 뒤 해당 값들을 세줍니다.

3. 세개의 행 중 하나라도 w.size()만큼 입력할 수 있다면 정답 문자열이므로 이를 ans에 push_back해줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        string firstRow = "qwertyuiop";
        string secondRow = "asdfghjkl";
        string thirdRow = "zxcvbnm";
        vector <string> ans;
        for(auto w : words) {
            int canFirst = 0, canSecond = 0, canThird = 0;
            for(auto c : w) {
                char lowerC = tolower(c); 
                for(auto f : firstRow) {
                    if(f == lowerC) {
                        canFirst++;
                    }
                }
                for(auto s : secondRow) {
                    if(s == lowerC) {
                        canSecond++;
                    }
                }
                for(auto t : thirdRow) {
                    if(t == lowerC) {
                        canThird++;
                    }
                }
            }
            if(canFirst == w.size() || canSecond == w.size() || canThird == w.size()) {
                ans.push_back(w);
            }
        }
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.