
问题
给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。
输入: [“Hello”, “Alaska”, “Dad”, “Peace”]
输出: [“Alaska”, “Dad”]
注意:
你可以重复使用键盘上同一字符。
你可以假设输入的字符串将只包含字母。
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.
Input: [“Hello”, “Alaska”, “Dad”, “Peace”]
Output: [“Alaska”, “Dad”]
Note:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.
示例
public class Program { public static void Main(string[] args) { var words = new string[] { "Hello", "Alaska", "Dad", "Peace" }; var res = FindWords(words); ShowArray(res); Console.ReadKey(); } private static void ShowArray(string[] array) { foreach(var num in array) { Console.Write($"{num} "); } Console.WriteLine(); } public static string[] FindWords(string[] words) { var res = new List<string>(); var line = new List<List<char>>() { new List<char> { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' } , new List<char>{ 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l' }, new List<char>{ 'z', 'x', 'c', 'v', 'b', 'n', 'm' }}; foreach(var word in words) { var list = new HashSet<int>(); foreach(var item in word) { for(var i = 0; i < 3; i++) { if(line[i].Contains(item)) list.Add(i); } if(list.Count > 1) break; } if(list.Count == 1) { res.Add(word); } } return res.ToArray(); } }
以上给出1种算法实现,以下是这个案例的输出结果:
Alaska Dad
分析:
该题的时间复杂度和单词的长度有关,设最长的单词长度为m,单词的数量为n,那么该题的时间复杂度为: 。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/3796。