LeetCode——Keyboard Row

LeetCode——Keyboard Row

Question

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.

Answer


class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        string str1 = "qwertyuiop";
        string str2 = "asdfghjkl";
        string str3 = "zxcvbnm";

        vector<string> res;
        for (string str : words) {
            char c = str[0] >= 97 ? str[0] : str[0] + 32;
            if (str1.find(c) != string::npos) {
                if (judge(str, str1))
                    res.push_back(str);
            } else if (str2.find(c) != string:: npos) {
                if (judge(str, str2))
                    res.push_back(str);
            } else {
                if (judge(str, str3))
                    res.push_back(str);
            }
        }
        return res;
    }

    int judge(string str, string str1) {
        int flag = 1;
        for (int i = 1; i < str.length(); i++) {
            char c = str[i] >= 97 ? str[i] : str[i] + 32;
            if (str1.find(c) == string::npos) {
                flag = 0;
                break;
            }
        }
        return flag;
    }
};
原文地址:https://www.cnblogs.com/zhonghuasong/p/6657598.html