500. Keyboard Row

2018/04/14 leetcode 共 935 字,约 3 分钟

Title

the problem link

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: You may use one character in the keyboard more than once. You may assume the input string will only contain letters of alphabet.

题目大意:给几个单词,假如这个单词可以用电脑键盘的一行字母表示,就返回

Solution

用map存储字母对应的行数,一次AC

//cpp:
class Solution {
public:
	vector<string> findWords(vector<string>& words) {
		string a[3] = { "qwertyuiop","asdfghjkl","zxcvbnm" };
		unordered_map<char, int> map1;
		vector<string> res;
		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < a[i].size(); j++) {
				map1[a[i][j]] = i + 1;
				map1[a[i][j]-32] = i + 1;
			}
		}
		for (int i = 0; i < words.size(); i++) {
			bool flag = true;
			for (int j = 1; j < words[i].size(); j++) {
				if (map1[words[i][j]] != map1[words[i][j-1]]) {
					flag = false;
					break;
				}
			}
			if (flag) {
				res.push_back(words[i]);
			}
		}
		return res;
	}
};

Search

    Table of Contents