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.
class Solution {
public String[] findWords(String[] words) {
String row1 = "qwertyuiop";
String row2 = "asdfghjkl";
String row3 = "zxcvbnm";
ArrayList<String> result = new ArrayList<String>();
int i = 0;
for(String word:words){
int n1 = 0, n2 = 0, n3 = 0;
for(char c:word.toCharArray()){
if(row1.indexOf(Character.toLowerCase(c))>=0) n1++;
if(row2.indexOf(Character.toLowerCase(c))>=0) n2++;
if(row3.indexOf(Character.toLowerCase(c))>=0) n3++;
if(n1*n2>0 || n1*n3>0 || n2*n3>0) break;
}
if(n1==word.length() || n2==word.length() || n3==word.length()) result.add(word);
}
String[] ans = result.stream().toArray(String[]::new);
return ans;
}
}
simple one line java solution using regular expression.
class Solution {
public String[] findWords(String[] words) {
return Stream.of(words).filter(s -> s.toLowerCase().matches("[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*")).toArray(String[]::new);
}
}