zoukankan      html  css  js  c++  java
  • 【leetcode】500. Keyboard Row

    问题描述:

    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:

    1. You may use one character in the keyboard more than once.
    2. You may assume the input string will only contain letters of alphabet.

    解法一:

    常规解法,用unordered_set存储每一行的字母,依次寻找判断。

     1 class Solution {
     2 public:
     3     vector<string> findWords(vector<string>& words) {
     4        unordered_set<char> row1 {'q', 'w', 'e', 'r', 't', 'y','u', 'i', 'o', 'p'};
     5         unordered_set<char> row2 {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'}; 
     6         unordered_set<char> row3 { 'z', 'x', 'c', 'v', 'b' ,'n', 'm'};
     7         vector<unordered_set<char>> rows {row1, row2, row3};
     8         
     9         
    10         vector<string> validWords;
    11         for(int i=0; i<words.size(); ++i){
    12             int row=0;
    13             
    14             for(int k=0; k<3; ++k){
    15                 if(rows[k].count((char)tolower(words[i][0])) > 0) row = k;
    16             }
    17             
    18             validWords.push_back(words[i]);
    19             for(int j=1; j<words[i].size(); ++j){
    20                 if(rows[row].count((char)tolower(words[i][j])) == 0){
    21                     validWords.pop_back();
    22                     break;
    23                 }
    24             }
    25             
    26         }
    27         return validWords;
    28     }
    29 };

    解法二:

    这种解法比较有启发性,看起来很有意思。

     1 class Solution {
     2 public:
     4 vector<string> findWords(vector<string>& words) 
     5 {
     6     vector<string> res;
     7     
     8     for(auto str : words)
     9     {
    10         bool r1 = str.find_first_of("QWERTYUIOPqwertyuiop") == string::npos ? false : true;
    11         bool r2 = str.find_first_of("ASDFGHJKLasdfghjkl") == string::npos ? false : true;
    12         bool r3 = str.find_first_of("ZXCVBNMzxcvbnm") == string::npos ? false : true;
    13         
    14         if(r1 + r2 + r3 == 1)
    15             res.push_back(str);
    16     }
    17     
    18     return res;
    19 }
    20     
    21 };
  • 相关阅读:
    Axis2创建WebService服务端接口+SoupUI以及Client端demo测试调用
    python 网络爬虫 scapy 下载 论坛帖子链接和标题
    scrapy抓中文,保存csv文件乱码解决方法
    python 3 map函数用法
    HTML基础信息笔记
    css提取数据2个常用方法
    Python3 scrapy 新手命令
    Python3.0 urllib request自己第一成功做出爬虫
    python geopandas读取保存文件中文属性乱码
    arcmap中dissolve时ERROR000210
  • 原文地址:https://www.cnblogs.com/SarahLiu/p/6702364.html
Copyright © 2011-2022 走看看