Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/500.html

500. Keyboard Row

Level

Easy

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.

Image text

Example:

Input: [“Hello”, “Alaska”, “Dad”, “Peace”]

Output: [“Alaska”, “Dad”]

Note:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.

Solution

For each letter, store its row. Then check each word to see whether the letters are in the same row. If so, add the word to the result array.

  • class Solution {
        public String[] findWords(String[] words) {
            Map<Character, Integer> letterRowMap = new HashMap<Character, Integer>();
            letterRowMap.put('q', 1);
            letterRowMap.put('w', 1);
            letterRowMap.put('e', 1);
            letterRowMap.put('r', 1);
            letterRowMap.put('t', 1);
            letterRowMap.put('y', 1);
            letterRowMap.put('u', 1);
            letterRowMap.put('i', 1);
            letterRowMap.put('o', 1);
            letterRowMap.put('p', 1);
            letterRowMap.put('a', 2);
            letterRowMap.put('s', 2);
            letterRowMap.put('d', 2);
            letterRowMap.put('f', 2);
            letterRowMap.put('g', 2);
            letterRowMap.put('h', 2);
            letterRowMap.put('j', 2);
            letterRowMap.put('k', 2);
            letterRowMap.put('l', 2);
            letterRowMap.put('z', 3);
            letterRowMap.put('x', 3);
            letterRowMap.put('c', 3);
            letterRowMap.put('v', 3);
            letterRowMap.put('b', 3);
            letterRowMap.put('n', 3);
            letterRowMap.put('m', 3);
            List<String> wordsList = new ArrayList<String>();
            for (String word : words) {
                String lowerCaseWord = word.toLowerCase();
                boolean flag = true;
                char[] array = lowerCaseWord.toCharArray();
                if (array.length == 0) {
                    wordsList.add(word);
                    continue;
                }
                char c0 = array[0];
                int prevRow = letterRowMap.get(c0);
                for (char c : array) {
                    int curRow = letterRowMap.get(c);
                    if (curRow != prevRow) {
                        flag = false;
                        break;
                    }
                    prevRow = curRow;
                }
                if (flag)
                    wordsList.add(word);
            }
            int length = wordsList.size();
            String[] rowWords = new String[length];
            for (int i = 0; i < length; i++)
                rowWords[i] = wordsList.get(i);
            return rowWords;
        }
    }
    
    ############
    
    class Solution {
        public String[] findWords(String[] words) {
            String s = "12210111011122000010020202";
            List<String> ans = new ArrayList<>();
            for (var w : words) {
                String t = w.toLowerCase();
                char x = s.charAt(t.charAt(0) - 'a');
                boolean ok = true;
                for (char c : t.toCharArray()) {
                    if (s.charAt(c - 'a') != x) {
                        ok = false;
                        break;
                    }
                }
                if (ok) {
                    ans.add(w);
                }
            }
            return ans.toArray(new String[0]);
        }
    }
    
  • // OJ: https://leetcode.com/problems/keyboard-row/
    // Time: O(N)
    // Space: O(1)
    const string keyboard[3] = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
    int m[26] = {};
    static const auto __init__ = []() {
        for (int i = 0; i < 3; ++i) {
            for (char c : keyboard[i]) m[c - 'a'] = i;
        }
        return 0;
    }();
    class Solution {
    public:
        vector<string> findWords(vector<string>& A) {
            vector<string> ans;
            for (auto &s : A) {
                int i = -1;
                for (char c : s) {
                    int j = m[tolower(c) - 'a'];
                    if (i == -1) i = j;
                    else if (j != i) {
                        i = -1;
                        break;
                    }
                }
                if (i != -1) ans.push_back(s);
            }
            return ans;
        }
    };
    
  • class Solution:
        def findWords(self, words: List[str]) -> List[str]:
            s1 = set('qwertyuiop')
            s2 = set('asdfghjkl')
            s3 = set('zxcvbnm')
            res = []
            for word in words:
                t = set(word.lower())
                if t <= s1 or t <= s2 or t <= s3:
                    res.append(word)
            return res
    
    ############
    
    class Solution(object):
      def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        ans = []
        d = {}
        row1 = "qwertyuiop"
        row2 = "asdfghjkl"
        row3 = "zxcvbnm"
        for r in row1:
          d[r] = 1.0
        for r in row2:
          d[r] = 2.0
        for r in row3:
          d[r] = 3.0
    
        for word in words:
          same = True
          pre = d[word[0].lower()]
          for c in word:
            if pre != d[c.lower()]:
              same = False
              break
            pre = d[c.lower()]
          if same:
            ans.append(word)
        return ans
    
    
  • func findWords(words []string) (ans []string) {
    	s := "12210111011122000010020202"
    	for _, w := range words {
    		x := s[unicode.ToLower(rune(w[0]))-'a']
    		ok := true
    		for _, c := range w[1:] {
    			if s[unicode.ToLower(c)-'a'] != x {
    				ok = false
    				break
    			}
    		}
    		if ok {
    			ans = append(ans, w)
    		}
    	}
    	return
    }
    
  • function findWords(words: string[]): string[] {
        const s = '12210111011122000010020202';
        const ans: string[] = [];
        for (const w of words) {
            const t = w.toLowerCase();
            const x = s[t.charCodeAt(0) - 'a'.charCodeAt(0)];
            let ok = true;
            for (const c of t) {
                if (s[c.charCodeAt(0) - 'a'.charCodeAt(0)] !== x) {
                    ok = false;
                    break;
                }
            }
            if (ok) {
                ans.push(w);
            }
        }
        return ans;
    }
    
    
  • public class Solution {
        public string[] FindWords(string[] words) {
            string s = "12210111011122000010020202";
            IList<string> ans = new List<string>();
            foreach (string w in words) {
                char x = s[char.ToLower(w[0]) - 'a'];
                bool ok = true;
                for (int i = 1; i < w.Length; ++i) {
                    if (s[char.ToLower(w[i]) - 'a'] != x) {
                        ok = false;
                        break;
                    }
                }
                if (ok) {
                    ans.Add(w);
                }
            }
            return ans.ToArray();
        }
    }
    

All Problems

All Solutions