500. 单词是否在键盘上的同一行 Keyboard Row

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

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.
    题意:判断单词中的每一个字母,在键盘上位置是否为同一行
HashSet的查找时间复杂度为O(n)
  1. static public string[] FindWords(string[] words) {
  2. List<string> resultArr = new List<string>();
  3. HashSet<char> line1 = new HashSet<char>() { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P' };
  4. HashSet<char> line2 = new HashSet<char>() { 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L' };
  5. HashSet<char> line3 = new HashSet<char>() { 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'Z', 'X', 'C', 'V', 'B', 'N', 'M' };
  6. foreach (string str in words) {
  7. if (Check(str, line3) || Check(str, line2) || Check(str, line1)) {
  8. resultArr.Add(str);
  9. }
  10. }
  11. return resultArr.ToArray();
  12. }
  13. static public bool Check(string str, HashSet<char> hashSet) {
  14. foreach (char c in str) {
  15. if (!hashSet.Contains(c)) {
  16. return false;
  17. }
  18. }
  19. return true;
  20. }





原文地址:https://www.cnblogs.com/xiejunzhao/p/7eba48d95dde2043b7402b1bf9257824.html