如果单词列表(words)中的一个单词包含牌照(licensePlate)中所有的字母,那么我们称之为完整词。在所有完整词中,最短的单词我们称之为最短完整词。
单词在匹配牌照中的字母时不区分大小写,比如牌照中的 "P" 依然可以匹配单词中的 "p" 字母。
我们保证一定存在一个最短完整词。当有多个单词都符合最短完整词的匹配条件时取单词列表中最靠前的一个。
牌照中可能包含多个相同的字符,比如说:对于牌照 "PP",单词 "pair" 无法匹配,但是 "supper" 可以匹配。
示例 1:
输入:licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
输出:"steps"
说明:最短完整词应该包括 "s"、"p"、"s" 以及 "t"。对于 "step" 它只包含一个 "s" 所以它不符合条件。同时在匹配过程中我们忽略牌照中的大小写。
示例 2:
输入:licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
输出:"pest"
说明:存在 3 个包含字母 "s" 且有着最短长度的完整词,但我们返回最先出现的完整词。
注意:
牌照(licensePlate)的长度在区域[1, 7]中。
牌照(licensePlate)将会包含数字、空格、或者字母(大写和小写)。
单词列表(words)长度在区间 [10, 1000] 中。
每一个单词 words[i] 都是小写,并且长度在区间 [1, 15] 中。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-completing-word
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
static void Main(string[] args)
{
string[] words = { "enough", "these", "play", "wide", "wonder", "box", "arrive", "money", "tax", "thus" };
string licensePlate = "OgEu755";
string c= ShortestCompletingWords( licensePlate,words);
Console.Write(c);
Console.ReadKey();
}
public static string ShortestCompletingWords(string licensePlate, string[] words)
{
string res = "";
//first,去除数字,转换为小写
licensePlate= System.Text.RegularExpressions.Regex.Replace(licensePlate, @"\d", "");
licensePlate = licensePlate.ToLower();
licensePlate = licensePlate.Replace(" ", "");
var dic = new Dictionary<char, int>();
List<string> reslist = new List<string>();
for (int i = 0; i < licensePlate.Length; i++)
{
if (dic.ContainsKey(licensePlate[i]))
{
dic[licensePlate[i]]++;
}
else
{
dic[licensePlate[i]] = 1;
}
}
foreach (var looks in words)
{
//依然统计looks的dictionary。
bool canForm = true;
var d = new Dictionary<char, int>();
foreach (var chr in looks)
{
if (d.ContainsKey(chr))
{
d[chr]++;
}
else
{
d.Add(chr, 1);
}
}
foreach (var item in dic)
{
if (!d.ContainsKey(item.Key))
{
//不满足条件
canForm = false;
break;
}
if (d[item.Key] >= item.Value)
{
canForm = true;
}
else
{
//不满足条件
canForm = false;
break;
}
}
if (canForm)
{
reslist.Add(looks);
}
}
//从集合中找到第一个数据
if (reslist.Count == 0)
return "";
res = reslist[0];
for (int i = 1; i < reslist.Count; i++)
{
if (reslist[i].Length < res.Length)
res = reslist[i];
}
return res;
}
上帝保佑,终于完成了这道题目,改了一小天。
解析:
参考类似的一题目:https://blog.csdn.net/us2019/article/details/104839560
深度解刨这类题,无非就是两个哈希表之间的 key\value的多少、大小的比较。结构就是这样的结构。