leetcode500. Keyboard Row

来源:互联网 发布:淘宝主图怎么做 编辑:程序博客网 时间:2024/05/29 03:35

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:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.

解法

正则匹配

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