Total Accepted: 12327 Total Submissions: 20383 Difficulty: Easy Contributors: Admin Given a List of Words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard like the image below.
American keyboard 
Example 1: Input: [“Hello”, “Alaska”, “Dad”, “Peace”] Output: [“Alaska”, “Dad”] Note: You may use one character in the keyboard more than once. You may assume the input string will only contain letters of alphabet. Subscribe to see which companies asked this question. 這個題的意思就是輸入一些單詞,如果這個單詞能用鍵盤上的一行就能打出來,就輸出它.
解法: 這里運用標準庫里的容器: unordered_set
class Solution {public: vector<string> findWords(vector<string>& words) { vector<string> res;//來一個string類的動態數組 unordered_set<char> row1{'q','w','e','r','t','y','u','i','o','p'};//存儲鍵盤上第一行的字母 unordered_set<char> row2{'a','s','d','f','g','h','j','k','l'};//存儲鍵盤上第二行的字母 unordered_set<char> row3{'z','x','c','v','b','n','m'};//存儲鍵盤上第三行的字母 for (string word : words) //for循環數組words,words的元素就是一個單詞 { int one = 0, two = 0, three = 0;//初始化計數器 for (char c : word) {//for循環數組word(一個單詞),word的元素即是字符 if (c < 'a') c += 32; if (row1.count(c)) one = 1;//count函數返回的是符合的元素的個數,如果沒有,則返回0,即false,大于0則為true if (row2.count(c)) two = 1; if (row3.count(c)) three = 1; if (one + two + three > 1) break;//即這個單詞只用一行是無法輸入完的 } if (one + two + three == 1) res.push_back(word); } return res; }};參考資料: https://discuss.leetcode.com/topic/77754/java-1-line-solution-via-regex-and-stream
新聞熱點
疑難解答