1. 程式人生 > >Keyboard Row

Keyboard Row

you charat i++ div false arr problem 分享 ont

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:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.
 1 public String[] findWords(String[] words) {
 2         if(words == null || words.length == 0){
 3             return words;
 4         }
 5         char [][]chars = {
 6                 {‘Q‘, ‘q‘,‘W‘, ‘w‘, ‘E‘, ‘e‘, ‘R‘, ‘r‘, ‘T‘, ‘t‘, ‘Y‘, ‘y‘, ‘U‘, ‘u‘, ‘I‘, ‘i‘, ‘O‘, ‘o‘, ‘P‘, ‘p‘},
 7                 {‘A‘, ‘a‘, ‘S‘, ‘s‘, ‘D‘, ‘d‘, ‘F‘, ‘f‘, ‘G‘, ‘g‘, ‘H‘, ‘h‘, ‘J‘, ‘j‘, ‘K‘, ‘k‘, ‘L‘, ‘l‘ },
8 {‘Z‘, ‘z‘, ‘X‘, ‘x‘, ‘C‘, ‘c‘, ‘V‘, ‘v‘, ‘B‘, ‘b‘, ‘N‘, ‘n‘, ‘M‘, ‘m‘} 9 }; 10 int[] c2Line = new int[58]; 11 for(int i = 0; i < chars.length; i++){ 12 for(int j = 0; j < chars[i].length; j++){ 13 c2Line[chars[i][j] - 65] = i;
14 } 15 } 16 List<String> result = new ArrayList<String>(); 17 for(String word : words){ 18 boolean isCan = true; 19 for(int i = 1; i < word.length(); i++){ 20 if(c2Line[word.charAt(0) - 65] != c2Line[word.charAt(i) - 65]){ 21 isCan = false; 22 break; 23 } //if 24 } //for 25 if(isCan){ 26 result.add(word); 27 } 28 } //for 29 String[] resultWords = result.toArray(new String[result.size()]); 30 return resultWords; 31 }

Keyboard Row