1. 程式人生 > >3.Keyboard Row

3.Keyboard Row

lis hashmap 鍵盤 () ++ problems 屬於 leet 題意

leetcode地址:https://leetcode.com/problems/keyboard-row/description/

題意:給你一個字符串數組,輸出一個新的數組,這個新的數組中的每一個字符串所有的字符屬於鍵盤上的同一行。

 1     public String[] findWords(String[] words) {
 2         String[] tmp = new String[]{"qwertyuiop","asdfghjkl","zxcvbnm"};
 3         Map<Character,Integer> map = new HashMap<Character,Integer>();
4 for(int i=0;i<tmp.length;i++) 5 { 6 char[] chars = tmp[i].toCharArray(); 7 for(char a:chars) 8 map.put(a,i); 9 } 10 11 List<String> result = new ArrayList<String>(); 12 for(int i=0;i<words.length;i++)
13 { 14 String str = words[i].toLowerCase(); 15 int index = map.get(str.charAt(0)); 16 boolean flag = true; 17 for(char a:str.toCharArray()) 18 { 19 if(map.get(a) != index) 20 flag = false; 21 }
22 if(flag) 23 result.add(words[i]); 24 } 25 return result.toArray(new String[0]); 26 27 }

3.Keyboard Row