Keyboard Row
Posted Just DO IT by luckygxf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Keyboard Row相关的知识,希望对你有一定的参考价值。
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.
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的主要内容,如果未能解决你的问题,请参考以下文章