단어 목록이 주어지면 표준 키보드 레이아웃의 한 행에서만 알파벳 문자를 사용하여 입력할 수 있는 단어를 찾아야 합니다.
따라서 입력이 ["hello","world","mom","dad","try","type","tom"]과 같으면 출력은 ["dad","try"가 됩니다. ,"유형"]
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
배열 출력 정의
-
oneRow :=참
-
하나의 맵 charToRowMap을 정의하면 {letter,line}, 문자는 키보드에 있는 문자, line은 키보드의 줄 번호와 같은 모든 쌍을 취합니다.
-
단어 배열의 각 단어에 대해 -
-
단어가 비어 있지 않으면 -
-
oneRow :=참
-
행 :=charToRowMap[tolower(단어[0])
-
for initialize i :=1, i <단어 크기일 때 업데이트(i 1 증가), −
-
charToRowMap[tolower(word[i])가 행과 같지 않으면 -
-
oneRow :=거짓
-
루프에서 나오세요
-
-
-
oneRow가 0이 아닌 경우 -
-
출력 끝에 단어 삽입
-
-
-
-
반환 출력
예시
더 나은 이해를 위해 다음 구현을 살펴보겠습니다. −
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<string> output;
bool oneRow = true;
unordered_map<char, int> charToRowMap{
{ 'q', 1 }, { 'w', 1 }, { 'e', 1 }, { 'r', 1 }, { 't', 1 }, { 'y', 1 }, { 'u', 1 },
{ 'i', 1 }, { 'o', 1 }, { 'p', 1 }, { 'a', 2 }, { 's', 2 }, { 'd', 2 }, { 'f', 2 }, { 'g', 2 }, { 'h', 2 }, { 'j', 2 }, { 'k', 2 }, { 'l', 2 }, { 'z', 3 }, { 'x', 3 }, { 'c', 3 }, { 'v', 3 }, { 'b', 3 }, { 'n', 3 }, { 'm', 3 }
};
for (auto word : words)
if (!word.empty()) {
oneRow = true;
int row = charToRowMap[tolower(word[0])];
for (int i = 1; i < word.length(); i++)
if (charToRowMap[tolower(word[i])] != row) {
oneRow = false;
break;
}
if (oneRow)
output.push_back(word);
}
return output;
}
};
main(){
Solution ob;
vector<string> v = {"hello","world","mom","dad","try","type","tom"};
print_vector(ob.findWords(v));
} 입력
{"hello","world","mom","dad","try","type","tom"} 출력
[dad, try, type, ]