首页 > 代码库 > Keyboard Row
Keyboard Row
1. Title
500. Keyboard Row
2. Http address
https://leetcode.com/problems/keyboard-row/?tab=Description
3. The question
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.
4. Code
public class Solution { public String[] findWords(String[] words) { Set<Character> hashSet1 = new HashSet<Character>(); Set<Character> hashSet2 = new HashSet<Character>(); Set<Character> hashSet3 = new HashSet<Character>(); Set sets[] = new HashSet[3]; sets[0] = hashSet1; sets[1] = hashSet2; sets[2] = hashSet3; hashSet1.add(‘Q‘); hashSet1.add(‘W‘); hashSet1.add(‘E‘); hashSet1.add(‘R‘); hashSet1.add(‘T‘); hashSet1.add(‘Y‘); hashSet1.add(‘U‘); hashSet1.add(‘I‘); hashSet1.add(‘O‘); hashSet1.add(‘P‘); hashSet2.add(‘A‘); hashSet2.add(‘S‘); hashSet2.add(‘D‘); hashSet2.add(‘F‘); hashSet2.add(‘G‘); hashSet2.add(‘H‘); hashSet2.add(‘J‘); hashSet2.add(‘K‘); hashSet2.add(‘L‘); hashSet3.add(‘Z‘); hashSet3.add(‘X‘); hashSet3.add(‘C‘); hashSet3.add(‘V‘); hashSet3.add(‘B‘); hashSet3.add(‘N‘); hashSet3.add(‘M‘); if (words == null || words.length <= 0) { return new String[0]; } int len = words.length; String[] re = new String[len]; int index = 0; for (int i = 0; i < len; i++) { String word = words[i].toUpperCase(); int wlen = word.length(); int tag = 0; int j = 0; if (sets[0].contains(word.charAt(0))) { tag = 0; } else if (sets[1].contains(word.charAt(0))) { tag = 1; } else { tag = 2; } j++; while (j < wlen) { if (!sets[tag].contains(word.charAt(j))) { break; } j++; } if (j == wlen) { re[index++] = words[i]; } } String[] res = new String[index]; for (int i = 0; i < index; i++) { res[i] = re[i]; } return res; } }
Keyboard Row
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。