Skip to content

Latest commit

 

History

History
86 lines (68 loc) · 2.43 KB

File metadata and controls

86 lines (68 loc) · 2.43 KB

https://leetcode-cn.com/problems/keyboard-row/solution/500jian-pan-xing-pythonjava-xun-huan-bi-bk09v/

难度:简单

题目

给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。

美式键盘 中:

  • 第一行由字符 "qwertyuiop" 组成。
  • 第二行由字符 "asdfghjkl" 组成。
  • 第三行由字符 "zxcvbnm" 组成。

提示:

  • 1 <= words.length <= 20
  • 1 <= words[i].length <= 100
  • words[i] 由英文字母(小写和大写字母)组成

示例

示例 1:
输入:words = ["Hello","Alaska","Dad","Peace"]
输出:["Alaska","Dad"]

示例 2:
输入:words = ["omk"]
输出:[]

示例 3:
输入:words = ["adsdf","sfd"]
输出:["adsdf","sfd"]

分析

由于用例范围很小,直接暴力循环即可。

解题

Python:

class Solution:
    def findWords(self, words):
        ret, lines = [], ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
        for word in  words:
            for line in lines:
                if not (set(word.lower()) - set(line)):
                    ret.append(word)
                    break
        return ret

Java:

class Solution {
    public String[] findWords(String[] words) {
        String[] lines = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
        ArrayList<String> s = new ArrayList<>();
        for (String word : words) {
            String lowWord = word.toLowerCase();
            outer:for (String line : lines) {
                for (int i = 0; i < word.length(); i++) {
                    if (!line.contains(lowWord.substring(i, i+1))) continue outer;
                }
                s.add(word);
            }
        }
        String[] ret = new String[s.size()];
        for (int i = 0; i < s.size(); i++) {
            ret[i] = s.get(i);
        }
        return ret;        
    }
}

欢迎关注我的公众号: 清风Python,带你每日学习Python算法刷题的同时,了解更多python小知识。

有喜欢力扣刷题的小伙伴可以加我微信(King_Uranus)互相鼓励,共同进步,一起玩转超级码力!

我的个人博客:https://qingfengpython.cn

力扣解题合集:https://github.com/BreezePython/AlgorithmMarkdown