[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的其他的代码思路也是这样的,不再多提

posted @ 2018-08-14 10:47  arcsinW  阅读(114)  评论(0编辑  收藏  举报