จากรายชื่อคำ เราต้องหาคำเหล่านั้นที่สามารถพิมพ์ได้โดยใช้ตัวอักษรของรูปแบบแป้นพิมพ์มาตรฐานเพียงแถวเดียว
ดังนั้น หากอินพุตเป็น ["hello","world","mom","dad","try","type","tom"] ผลลัพธ์จะเป็น ["dad","try" ,"ประเภท"]
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -
-
กำหนดเอาต์พุตอาร์เรย์
-
oneRow :=จริง
-
กำหนดหนึ่งแผนที่ charToRowMap ซึ่งจะนำคู่ทั้งหมดเช่น {letter,line} ตัวอักษรคือตัวอักษรที่ปรากฏบนแป้นพิมพ์ และ line คือหมายเลขบรรทัดบนแป้นพิมพ์
-
สำหรับแต่ละคำในอาร์เรย์คำ -
-
ถ้าคำนั้นไม่ว่างเปล่า −
-
oneRow :=จริง
-
แถว :=charToRowMap[tolower(word[0])
-
สำหรับการเริ่มต้น i :=1 เมื่อฉัน <ขนาดของคำ อัปเดต (เพิ่ม i ขึ้น 1) ทำ −
-
ถ้า charToRowMap[tolower(word[i]) ไม่เท่ากับ row ดังนั้น −
-
แถวเดียว :=เท็จ
-
ออกจากวง
-
-
-
ถ้า oneRow ไม่ใช่ศูนย์ ดังนั้น −
-
ใส่คำที่ส่วนท้ายของผลลัพธ์
-
-
-
-
ส่งคืนเอาต์พุต
ตัวอย่าง
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
#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, ]