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.


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.

  1. You may assume the input string will only contain letters of alphabet.
class Solution {
public:
    vector<string> findWords(vector<string>& words) {
        string rows[] = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
        vector<string> vs;
        for (int i = 0; i < words.size(); i++)
        {
            string s = words[i];
            int r = -1;
            int j = 0;
            for (j = 0; j < s.size(); j++) {
                if (r == -1) {
                    while (r < 2) {
                        r++;
                        if (string::npos != rows[r].find(tolower(s[j]))) {
                            break;
                        }
                    }
                } else {
                    if (string::npos == rows[r].find(tolower(s[j]))) {
                           break;
                    }
                }
            }
            if (j == s.size()) {
                vs.push_back(s);
            }
        }
        return vs;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章