问题描述
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
思路
提交
ublic class Solution {
static int[] alphaUpper = new int[26];
static int[] alphaLower = new int[26];
static {
alphaUpper[(int)('Q' - 'A')] = 1;
alphaUpper[(int)('W' - 'A')] = 1;
alphaUpper[(int)('E' - 'A')] = 1;
alphaUpper[(int)('R' - 'A')] = 1;
alphaUpper[(int)('T' - 'A')] = 1;
alphaUpper[(int)('Y' - 'A')] = 1;
alphaUpper[(int)('U' - 'A')] = 1;
alphaUpper[(int)('I' - 'A')] = 1;
alphaUpper[(int)('O' - 'A')] = 1;
alphaUpper[(int)('P' - 'A')] = 1;
alphaLower[(int)('q' - 'a')] = 1;
alphaLower[(int)('w' - 'a')] = 1;
alphaLower[(int)('e' - 'a')] = 1;
alphaLower[(int)('r' - 'a')] = 1;
alphaLower[(int)('t' - 'a')] = 1;
alphaLower[(int)('y' - 'a')] = 1;
alphaLower[(int)('u' - 'a')] = 1;
alphaLower[(int)('i' - 'a')] = 1;
alphaLower[(int)('o' - 'a')] = 1;
alphaLower[(int)('p' - 'a')] = 1;
alphaUpper[(int)('A' - 'A')] = 2;
alphaUpper[(int)('S' - 'A')] = 2;
alphaUpper[(int)('D' - 'A')] = 2;
alphaUpper[(int)('F' - 'A')] = 2;
alphaUpper[(int)('G' - 'A')] = 2;
alphaUpper[(int)('H' - 'A')] = 2;
alphaUpper[(int)('J' - 'A')] = 2;
alphaUpper[(int)('K' - 'A')] = 2;
alphaUpper[(int)('L' - 'A')] = 2;
alphaLower[(int)('a' - 'a')] = 2;
alphaLower[(int)('s' - 'a')] = 2;
alphaLower[(int)('d' - 'a')] = 2;
alphaLower[(int)('f' - 'a')] = 2;
alphaLower[(int)('g' - 'a')] = 2;
alphaLower[(int)('h' - 'a')] = 2;
alphaLower[(int)('j' - 'a')] = 2;
alphaLower[(int)('k' - 'a')] = 2;
alphaLower[(int)('l' - 'a')] = 2;
alphaUpper[(int)('Z' - 'A')] = 3;
alphaUpper[(int)('X' - 'A')] = 3;
alphaUpper[(int)('C' - 'A')] = 3;
alphaUpper[(int)('V' - 'A')] = 3;
alphaUpper[(int)('B' - 'A')] = 3;
alphaUpper[(int)('N' - 'A')] = 3;
alphaUpper[(int)('M' - 'A')] = 3;
alphaLower[(int)('z' - 'a')] = 3;
alphaLower[(int)('x' - 'a')] = 3;
alphaLower[(int)('c' - 'a')] = 3;
alphaLower[(int)('v' - 'a')] = 3;
alphaLower[(int)('b' - 'a')] = 3;
alphaLower[(int)('n' - 'a')] = 3;
alphaLower[(int)('m' - 'a')] = 3;
}
public String[] findWords(String[] words) {
ArrayList<String> array = new ArrayList<>();
for (String word : words) {
int mark = 0;
int length = word.length();
for (int i = 0; i < length; i++) {
char c = word.charAt(i);
if (c >= '0' && c <= '9') {
mark |= 1;
} else if (c >= 'a' && c <= 'z') {
mark |= 1 << (alphaLower[(int)(c - 'a')]);
} else if (c >= 'A' && c <= 'Z') {
mark |= 1 << (alphaUpper[(int)(c - 'A')]);
}
}
if ((mark & (mark - 1)) == 0) {
array.add(word);
}
}
String[] result = new String[array.size()];
result = array.toArray(result);
return result;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。