#leetcode#500 Keyboard Row

来源:互联网 发布:女性 音乐家 知乎 编辑:程序博客网 时间:2024/05/22 11:47

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.


American keyboard


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.

======================================================================================================

没有太动脑子想一些简洁的代码, 通过这个题发现自己对  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]);    }}


原创粉丝点击