tinycodinglm / cp /cp-10009.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
2.52 kB
opencode trace
System You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

User

Problem: Keyboard Row (Difficulty: Easy)
Tags: Array, Hash Table, String

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.
Note that the strings are case-insensitive, both lowercased and uppercased of the same letter are treated as if they are at the same row.
In the American keyboard:

Example 1:
Input: words = ["Hello","Alaska","Dad","Peace"]
Output: ["Alaska","Dad"]
Explanation:
Both "a" and "A" are in the 2nd row of the American keyboard due to case insensitivity.

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

Example 3:
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).
Assistant

Time: O(n)

Space: O(1)

class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
rows = [set(['q', 'w', 'e', 'r', 't', 'y','u', 'i', 'o', 'p']),
set(['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']),
set(['z', 'x', 'c', 'v', 'b' ,'n', 'm'])]

markdown
result = []
    for word in words:
        k = 0
        for i in range(len(rows)):
            if word[0].lower() in rows[i]:
                k = i
                break
        for c in word:
            if c.lower() not in rows[k]:
                break
        else:
            result.append(word)
    return result

class Solution2(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
keyboard_rows = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']
single_row_words = []
for word in words:
for row in keyboard_rows:
if all(letter in row for letter in word.lower()):
single_row_words.append(word)
return single_row_words