500. Keyboard Row
Easy
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:
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.
package leetcode.easy; public class KeyboardRow { private static void print_arr(String[] strs) { for (String str : strs) { System.out.print(str + " "); } System.out.println(); } private java.util.HashSet<Character> set1 = new java.util.HashSet<Character>(); private java.util.HashSet<Character> set2 = new java.util.HashSet<Character>(); private java.util.HashSet<Character> set3 = new java.util.HashSet<Character>(); public String[] findWords(String[] words) { char[] chs1 = { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' }; char[] chs2 = { 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l' }; char[] chs3 = { 'z', 'x', 'c', 'v', 'b', 'n', 'm' }; boolean flag1 = false; boolean flag2 = false; boolean flag3 = false; java.util.LinkedList<String> result = new java.util.LinkedList<String>(); int j = 0; for (int i = 0; i < chs1.length; i++) { set1.add(chs1[i]); } for (int i = 0; i < chs2.length; i++) { set2.add(chs2[i]); } for (int i = 0; i < chs3.length; i++) { set3.add(chs3[i]); } for (int i = 0; i < words.length; i++) { String current = words[i].toLowerCase(); flag1 = false; flag2 = false; flag3 = false; for (j = 0; j < current.length(); j++) { char ch = current.charAt(j); if (set1.contains(ch)) { flag1 = true; } else if (set2.contains(ch)) { flag2 = true; } else if (set3.contains(ch)) { flag3 = true; } if ((flag1 && !flag2 && !flag3) || (!flag1 && flag2 && !flag3) || (!flag1 && !flag2 && flag3)) { continue; } else { break; } } if (j == current.length()) { if ((flag1 && !flag2 && !flag3) || (!flag1 && flag2 && !flag3) || (!flag1 && !flag2 && flag3)) { result.add(words[i]); } } } return result.toArray(new String[0]); } @org.junit.Test public void test() { String[] words = { "Hello", "Alaska", "Dad", "Peace" }; print_arr(findWords(words)); } }