Day 23 - Keyboard Row

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
废话不多说开始今天的解题Day~


500. Keyboard Row

Question

Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.

In the American keyboard:

  • the first row consists of the characters "qwertyuiop",
  • the second row consists of the characters "asdfghjkl", and
  • the third row consists of the characters "zxcvbnm".


Example

Example1

Input: words = ["Hello","Alaska","Dad","Peace"]
Output: ["Alaska","Dad"]

Example2

Input: words = ["omk"]
Output: []

Example3

Input: words = ["adsdf","sfd"]
Output: ["adsdf","sfd"]

Constraints

  • 1 <= words.length <= 20
  • 1 <= words[i].length <= 100
  • words[i] consists of English letters (both lowercase and uppercase).

解题

题目

首先先简单的翻译一下题目
给一组阵列的字串,要判断其中每个字使用到的字母是不是都在键盘上的同一列。

Think

作法大致上是这样

  • 用一个dictionary存每个字母对应在键盘上的那一列,然後一个字一个字去判断只要其中有一个字跟前一个字的row不同就跳出判断这个字串的回圈,往下个字串找。
  • C再补上,先睡啦。

Code

Python

class Solution:
    def findWords(self, words: List[str]) -> List[str]:
        dict = {'Q':1, 'W':1, 'E':1, 'R':1, 'T':1, 'Y':1, 'U':1, 'I':1, 'O':1, 'P':1, 
               'A':2, 'S':2, 'D':2, 'F':2, 'G':2, 'H':2, 'J':2, 'K':2, 'L':2,
               'Z':3, 'X':3, 'C':3, 'V':3, 'B':3, 'N':3, 'M':3}
        ans = []
        flag = False
        
        for word in words:
            row = 0
            for index in range(len(word)):
                if len(word) == 1:
                    flag = True
                    
                if row != 0:
                    if row == dict[word[index].upper()]:
                        flag = True
                        continue
                    else:
                        flag = False
                        break
                else:
                    row = dict[word[index].upper()]
            
            if flag:
                ans.append(word)
            
        return ans
                
            

C


Result

  • Python

  • C

大家明天见/images/emoticon/emoticon29.gif


<<:  DAY24神经网路(续二)

>>:  Day23 create React Navigation

day10 轨迹 (雷)没有就等着被电到飞上天

来部落格看图文并茂文章 补觉鸣诗 前面说防火墙 我们会设定 log 记录功能 而一般防火墙内建空间不...

威胁建模(threat modeling)的步骤

-威胁建模(来源:CSSLP CBK) 根据CSSLP CBK,可以通过以下方式进行威胁建模: 1...

Day.23 Binary Search Tree

终於讲到树,快接近尾声了(烟 二元搜寻图(Binary Search Tree)是一种很高效的资料结...

[ 卡卡 DAY 21 ] - React Native 资料手机存起来 AsyncStorage

如果怕手机关掉东西就不见了 来使用 AsyncStorage 将状态存到手机也就是 local s...

Day9 重叠条件配对池 Overlapping MatchProfiles

在一些比较普通的应用场景,我们产生一个 matches 的流程会像是,由 Director 轮询呼叫...