【LeetCode】500. Keyboard Row

问题描述

问题链接:https://leetcode.com/problems/keyboard-row/#/description

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.

我的代码

这题的思路非常简单,我就直接贴代码了。遇到的坑主要是API不记得了。以后会把学过的Trick整理出来,方便今后复习。

public class Solution {
    private static String rowOne = "qwertyuiopQWERTYUIOP";
    private static String rowTwo = "asdfghjklASDFGHJKL";
    private static String rowThree = "zxcvbnmZXCVBNM";

    public String[] findWords(String[] words) {
        /*
        思路是首先创建3个列表,分别包含键盘中3行的字母的大小写,
        然后遍历输入的单词,判断每个单词的所有字母是不是都出现在同一个列表中,
        如果是,那么这个单词符合要求,否则不符合要求
        */
        List<String> wordList = new ArrayList<String>();
        for(String word : words){
           if(canInput(word)){
               wordList.add(word);
           }
        }

        String[] results = new String[wordList.size()];
        return wordList.toArray(results);
    }

    private boolean canInput(String word){

        char c = word.charAt(0);
        String checkRow = rowThree;
        if(rowOne.indexOf(c) >= 0){
            checkRow = rowOne;
        }else if(rowTwo.indexOf(c) >= 0){
            checkRow = rowTwo;
        }

        for(int i = 1; i < word.length(); i++){
            char ch = word.charAt(i);
            if(checkRow.indexOf(ch) < 0){
                return false;
            }
        }

        return true;
    }
}

这次我打败了98.38%的Java代码!哈哈哈好开心。

讨论区

来,再到讨论区看看大神们的代码。

Short Easy Java with Explanation

链接地址:https://discuss.leetcode.com/topic/77773/short-easy-java-with-explanation

 public string[] FindWords(string[] words) 
    {
        int[] row1 = ToCountArr("qwertyuiop");
        int[] row2 = ToCountArr("asdfghjkl");
        int[] row3 = ToCountArr("zxcvbnm");

        return words.Where(w => All(row1, w) || All(row2, w) || All(row3, w)).ToArray();
    }

    public int[] ToCountArr(string s)
    {
        int[] arr = new int[26];
        foreach (char c in s)
        {
            arr[c - 'a'] = 1;
        }
        return arr;
    }

    public bool All(int[] row, string input)
    {
        foreach (char c in input.ToLower())
        {
            if (row[c-'a'] == 0) return false;
        }
        return true;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值