LeetCode500. Keyboard Row [C++]

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:

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

解题思路:

将三行字母放入map中,以字母为键,以行数为值。

对words中的每个word进行判断,以word中的第一个值为key,后面的与key不同则不是ans。

值得注意的是:word中的大小写要统一。

class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        vector<char> arr1={'q','w','e','r','t','y','u','i','o','p'};
        vector<char> arr2={'a','s','d','f','g','h','j','k','l'};
        vector<char> arr3={'z','x','c','v','b','n','m'};
        map<char,int> m;
        for(int i=0;i<arr1.size();i++)
        {
            m[arr1[i]]=1;
        }
        for(int i=0;i<arr2.size();i++)
        {
            m[arr2[i]]=2;
        }
        for(int i=0;i<arr3.size();i++)
        {
            m[arr3[i]]=3;
        }
        vector<string> ans;
        for(int i=0;i<words.size();i++)
        {
            string word=words[i];
            bool flag=true;
            for(int j=0;j<words[i].size();j++)
            {
                if(word[j]>='A'&&word[j]<='Z')
                    word[j]=word[j]-'A'+'a';
                int key=m[word[0]];
                if(m[word[j]]!=key)
                    flag=false;
            }
            if(flag)
                ans.push_back(words[i]);
        }            
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/ueh286/article/details/91896787