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.
class Solution { public String[] findWords(String[] word) { String[] words = new String[word.length]; for(int i = 0; i < word.length; i++) words[i] = word[i]; ArrayList<String> list = new ArrayList(); ArrayList<String> res = new ArrayList(); if(words.length == 0 || words == null) return new String[]{}; list.add("QWERTYUIOP"); list.add("ASDFGHJKL"); list.add("ZXCVBNM"); Set<Character> s1 = new HashSet(); for(char c: list.get(0).toCharArray()) s1.add(c); Set<Character> s2 = new HashSet(); for(char c: list.get(1).toCharArray()) s2.add(c); Set<Character> s3 = new HashSet(); for(char c: list.get(2).toCharArray()) s3.add(c); for(int i = 0; i < words.length; i++){ words[i] = words[i].toUpperCase(); int count = 0; int real = 0; if(s1.contains(words[i].charAt(0))) {count = 1; real = words[i].length();} if(s2.contains(words[i].charAt(0))) {count = 2; real = words[i].length() * 2;} if(s3.contains(words[i].charAt(0))) {count = 3; real = words[i].length() * 3;} for(int j = 1; j < words[i].length(); j++){ char c = words[i].charAt(j); if(s1.contains(c)) count += 1; if(s2.contains(c)) count += 2; if(s3.contains(c)) count += 3; } if(count == real) res.add(word[i]); } String[] resu = new String[res.size()]; for(int i = 0; i < res.size(); i++) resu[i] = res.get(i); return resu; } }
论如何把简单问题复杂化
class Solution { public String[] findWords(String[] word) { String[] words = new String[word.length]; for(int i = 0; i < word.length; i++) words[i] = word[i]; ArrayList<String> list = new ArrayList(); ArrayList<String> res = new ArrayList(); if(words.length == 0 || words == null) return new String[]{}; list.add("QWERTYUIOPqwertyuiop"); list.add("ASDFGHJKLasdfghjkl"); list.add("ZXCVBNMzxcvbnm"); for(int i = 0; i < words.length; i++){ int count = 0; int real = 0; int le = words[i].length(); char first = words[i].charAt(0); if(list.get(0).indexOf(first) >= 0) {count = 1; real = le;} if(list.get(1).indexOf(first) >= 0) {count = 2; real = le * 2;} if(list.get(2).indexOf(first) >= 0) {count = 3; real = le * 3;} for(int j = 1; j < words[i].length(); j++){ char c = words[i].charAt(j); if(list.get(0).indexOf(c) >= 0) count += 1; if(list.get(1).indexOf(c) >= 0) count += 2; if(list.get(2).indexOf(c) >= 0) count += 3; } if(count == real) res.add(word[i]); } String[] resu = new String[res.size()]; for(int i = 0; i < res.size(); i++) resu[i] = res.get(i); return resu; } }
版本2,不用set,用indexOf判断