| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.KeyboardRow; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class KeyboardRowLookup : IKeyboardRow |
| | | 16 | | { |
| | 1 | 17 | | private static readonly byte[] CharIndexToRow = |
| | 1 | 18 | | [ |
| | 1 | 19 | | 1, 2, 2, 1, 0, 1, 1, 1, 0, 1, 1, 1, 2, 2, 0, 0, 0, 0, 1, 0, 0, 2, 0, 2, 0, 2 |
| | 1 | 20 | | ]; |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Time complexity - O(n) |
| | | 24 | | /// Space complexity - O(1) |
| | | 25 | | /// </summary> |
| | | 26 | | /// <param name="words"></param> |
| | | 27 | | /// <returns></returns> |
| | | 28 | | public string[] FindWords(string[] words) |
| | 3 | 29 | | { |
| | 3 | 30 | | var result = new List<string>(words.Length); |
| | | 31 | | |
| | 23 | 32 | | foreach (var word in words) |
| | 7 | 33 | | { |
| | 7 | 34 | | if (IsSingleRow(word)) |
| | 4 | 35 | | { |
| | 4 | 36 | | result.Add(word); |
| | 4 | 37 | | } |
| | 7 | 38 | | } |
| | | 39 | | |
| | 3 | 40 | | return result.ToArray(); |
| | 3 | 41 | | } |
| | | 42 | | |
| | | 43 | | private static bool IsSingleRow(string word) |
| | 7 | 44 | | { |
| | 7 | 45 | | var firstRow = GetRow(word[0]); |
| | | 46 | | |
| | 42 | 47 | | for (var i = 1; i < word.Length; i++) |
| | 17 | 48 | | { |
| | 17 | 49 | | var c = word[i]; |
| | | 50 | | |
| | 17 | 51 | | if (GetRow(c) == firstRow) |
| | 14 | 52 | | { |
| | 14 | 53 | | continue; |
| | | 54 | | } |
| | | 55 | | |
| | 3 | 56 | | return false; |
| | | 57 | | } |
| | | 58 | | |
| | 4 | 59 | | return true; |
| | 7 | 60 | | } |
| | | 61 | | |
| | | 62 | | private static int GetRow(char c) |
| | 24 | 63 | | { |
| | 24 | 64 | | var charIndex = GetCharIndex(c); |
| | | 65 | | |
| | 24 | 66 | | return CharIndexToRow[charIndex]; |
| | 24 | 67 | | } |
| | | 68 | | |
| | | 69 | | private static int GetCharIndex(char c) |
| | 24 | 70 | | { |
| | 24 | 71 | | return (c | 32) - 'a'; |
| | 24 | 72 | | } |
| | | 73 | | } |