#leetcode#500 Keyboard Row
阿新 • • 發佈:2018-12-27
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.
======================================================================================================
沒有太動腦子想一些簡潔的程式碼, 通過這個題發現自己對 Arrays.asList(), list.toArray(), hashset.addAll() 這幾個method用的不熟
public class Solution { public String[] findWords(String[] words) { if(words == null || words.length == 0) return new String[]{}; List<String> res = new ArrayList<>(); Set<Character> set1 = new HashSet<>(); Set<Character> set2 = new HashSet<>(); Set<Character> set3 = new HashSet<>(); Character[] arr1 = new Character[]{'Q','q','W','w','E','e','R','r','T','t','Y','y','U','u','I','i','O','o','P','p'}; Character[] arr2 = new Character[]{'A','a','S','s','D','d','F','f','G','g','H','h','J','j','K','k','L','l'}; Character[] arr3 = new Character[]{'Z','z','X','x','C','c','V','v','B','b','N','n','M','m'}; set1.addAll(Arrays.asList(arr1)); set2.addAll(Arrays.asList(arr2)); set3.addAll(Arrays.asList(arr3)); for(String s : words){ boolean row1 = false; boolean row2 = false; boolean row3 = false; for(int i = 0; i < s.length(); i++){ Character c = s.charAt(i); if(set1.contains(c)) row1 = true; else if(set2.contains(c)) row2 = true; else if(set3.contains(c)) row3 = true; } if((row1 && !row2 && ! row3) || (!row1 && row2 && !row3) || (!row1 && !row2 && row3)){ res.add(s); } } // String[] result = new String[res.size()]; //also works // return res.toArray(result); return res.toArray(new String[0]); } }