首页 > 学院 > 开发设计 > 正文

500. Keyboard Row

2019-11-06 06:31:31
字体:
来源:转载
供稿:网友

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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表