2018年2月22日 星期四

[LeetCode] 500. Keyboard Row

轉自LeetCode

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.

American keyboard

Example 1:
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>

想法如下
  • 將每個 row 做分群。可以用 set 或是 bit mask,這次使用 bit mask
  • 分群 : QWERTYUIOP -> 001,ASDFGHJKL -> 010,ZXCVBNM -> 100
  • 將每個字串裡面的字元,對 mask = 111 做 AND,如果最後 mask不為 0,就是要的答案
code 如下

C++(參考解法)

Java

沒有留言:

張貼留言