Leetcode练习 500. Keyboard Row

    xiaoxiao2021-03-25  56

    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.

    用了一个Map来保存各字符的对应层次信息,之后遍历各字符串进行判断,相对来说效率还是低了点。

    之后在网上看到一个用正则式子匹配的,感觉挺不错的

    public class Solution { public String[] findWords(String[] words) { Map<Character, Integer> m = new HashMap<>(); List<String> a = new ArrayList<>(); m.put('a', 2);m.put('b', 3);m.put('c', 3);m.put('d', 2);m.put('e', 1);m.put('f', 2);m.put('g', 2); m.put('h', 2);m.put('i', 1);m.put('j', 2);m.put('k', 2);m.put('l', 2);m.put('m', 3);m.put('n', 3); m.put('o', 1);m.put('p', 1);m.put('q', 1);m.put('r', 1);m.put('s', 2);m.put('t', 1); m.put('u', 1);m.put('v', 3);m.put('w', 1);m.put('x', 3);m.put('y', 1);m.put('z', 3); for(String s : words) { int level=m.get(s.toLowerCase().charAt(0)); int flag=0; for(int i=1; i<s.length(); i++) { if(m.get(s.toLowerCase().charAt(i))!=level) { flag = 1; break; } } if(flag==0) { a.add(s); } } String[] ss = new String[a.size()]; for(int i=0; i<a.size(); i++) { ss[i] = a.get(i); } return ss; } } 转:

    public class Solution { public String[] findWords(String[] words) { String[] result = null; if (words != null) { List<String> list = new ArrayList<>(); String regex = "[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*"; for (String str : words) { if (str.toLowerCase().matches(regex)) { list.add(str); } } result = new String[list.size()]; for (int i = 0; i < list.size(); i++) { result[i] = list.get(i); } } return result; } }

    转载请注明原文地址: https://ju.6miu.com/read-37301.html

    最新回复(0)