此题视频讲解: https://blog.youkuaiyun.com/us2019/article/details/89361015
这个题真的好!!
var list = new HashSet<int>(); 用这个计数(代替了传统的int o=0;只需要new 就可以了)
关键位置:
for(var i = 0; i < 3; i++) {
if(line[i].Contains(item)) list.Add(i);
}
if(list.Count > 1) break;
解释:判断第一个集合里有没有,如果第一个集合有 数量加一,如果第二个集合也有,那么第二个集合也加一
如果循环完成数量==1 记录,>1 则break;
答案:
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();
}
视频里面的解题:
public string[] FindWords(string[] words) {
HashSet<char> row1 = new HashSet<char>(){'q','w','e','r','t','y','u','i','o','p'};
HashSet<char> row2 = new HashSet<char>(){'a','s','d','f','g','h','j','k','l'};
HashSet<char> row3 = new HashSet<char>(){'z','x','c','v','b','n','m'};
List<string> output = new List<string>();
foreach(string word in words)
{
string wordLower = word.ToLower();
if(IsPresentInRow(wordLower,row1) || IsPresentInRow(wordLower,row2) || IsPresentInRow(wordLower,row3))
{
output.Add(word);
}
}
return output.ToArray();
}
private bool IsPresentInRow(string input, HashSet<char> currentRow)
{
if(string.IsNullOrEmpty(input))
return false;
for(int i =0;i<input.Length;i++)
{
if(!currentRow.Contains(input[i]))
return false;
}
return true;
}