C++ 中的鍵盤行
給定一個單詞列表,我們需要找到那些僅使用標準鍵盤佈局上的某一行字母即可鍵入的單詞。
因此,如果輸入類似於 ["hello","world","mom","dad","try","type","tom"],那麼輸出將為 ["dad","try","type"]
為了解決此問題,我們將遵循以下步驟 −
定義一個數組 output
oneRow := true
定義一個對映 charToRowMap,這將獲取所有這樣的對 {letter,line},其中 letter 是鍵盤上的字母,而 line 是鍵盤上的行號。
對於 words 陣列中的每個單詞 -
如果單詞不為空,則 -
oneRow := true
row := charToRowMap[tolower(word[0])
對於從 1 開始的初始值 i,當 i < word 的大小時,更新 (將 i 加 1),執行 -
如果 charToRowMap[tolower(word[i]) 不等於 row,則 -
oneRow := false
退出迴圈
如果 oneRow 非零,則 -
在 output 的末尾插入 word
返回 output
示例
我們來看一下以下實現,以便更好地理解 −
#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, ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP