500. 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.

 

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.

大致意思是输入一个数组,找到其中是由同一行字母组成的字符串组成新的数组

思路很简单,使用hashmap存储一个键值对,键是每个字母,值是1,2,3。对于输入的字符串判断每个字符的hashmap的值是否一样即可

public String[] findWords(String[] words) {
       ArrayList<String> list = new ArrayList();
            String arr1[] = {"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"};
            String arr2[] = {"a", "s", "d", "f", "g", "h", "j", "k", "l"};
            String arr3[] = {"z", "x", "c", "v", "b", "n", "m"};
            HashMap temp = new HashMap();
            for(String s:arr1)
            {
                temp.put(s, 1);
            }
             for(String s:arr2)
            {
                 temp.put(s, 2);
            }
             for(String s:arr3)
            {
                 temp.put(s, 3);
            }
            for(int i=0;i<words.length;i++)
            {
                int judge = 0;
                for(int j=0;j<words[i].length();j++)
                {
                    if (temp.get("" + words[i].toLowerCase().charAt(0)) != temp.get("" + words[i].toLowerCase().charAt(j))) 
                    {
                        judge = 1;
                        break;
                    }
                }
                if(judge != 1)
                {
                    list.add(words[i]);
                }
            }
            String[] ans = new String[list.size()];
            return (String[]) list.toArray(ans);
    }

 

posted @ 2018-01-02 14:11  icychen  阅读(178)  评论(0编辑  收藏  举报