LeetCode: 500. Keyboard Row

来源:互联网 发布:让mac变成显示器 编辑:程序博客网 时间:2024/06/05 21:04

LeetCode: 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 {    String[] keyboards = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};    public String[] findWords(String[] words) {        int[] result = new int[words.length];        int n = 0;        for (int j = 0; j < words.length; j++) {            String wor = words[j].toLowerCase();            int line = -1;            for (int i = 0; i < keyboards.length; i++) {                String one = wor.substring(0, 1);                if (keyboards[i].contains(one)) {                    line = i;                }            }            boolean flag = true;            for (int i = 0; i < wor.length(); i++) {                if (!keyboards[line].contains(wor.substring(i, i + 1))) {                    flag = false;                    break;                }            }            if (flag == true) {                result[n] = j;                n++;            }        }        String[] results = new String[n];        for (int i = 0; i < n ; i++) {            results[i] = words[result[i]];        }        return results;    }}
原创粉丝点击