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.

    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.


    判断一个单词是否只用键盘的一行就能敲出来

    先做一个表,把每个字母和键盘的行号对应起来,再判断一个单词里的所有字母行号是否一致

    bool isValid(string word)
    {
        int dic[26] = {1,2,2,1,0,1,1,1,0,1,1,1,2,2,0,0,0,0,1,0,0,2,0,2,0,2};
        int row = word[0] >= 'a' ? dic[word[0] - 'a'] : dic[word[0] - 'A'];
    
        for (int j = 1; j < word.size(); j++)
        {
            int tmp = word[j] >= 'a' ? dic[word[j] - 'a'] : dic[word[j] - 'A'];
            if (tmp != row)
            {
                return false;
            }
        }
    
        return true;
    }
    
    vector<string> findWords(vector<string>& words) {
        vector<string> result;
    
        for(int i = 0; i < words.size(); i++)
        {
            string str = words.at(i);
    
            if (isValid(str))
            {
                result.push_back(str);
            }
        }
    
        return result;
    }
    

    LeetCode的其他的代码思路也是这样的,不再多提

  • 相关阅读:
    微信小程序与用户交互
    洛谷P2066 机器分配
    巴蜀3540 -- 【Violet 6 最终话】蒲公英
    POJ1984 Navigation Nightmare
    洛谷P1387 最大正方形
    洛谷P2679 子串
    洛谷P2057 善意的投票
    Bzoj 2726 SDOI 任务安排
    POJ2761 Feed the dogs
    P1272 重建道路
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9473187.html
Copyright © 2011-2022 走看看