public class Solution { public string ConvertString(string pattern) { var dic = new Dictionary<char, int>(); int code = 0; var str = ""; for (int i = 0; i < pattern.Length; i++) { if (!dic.ContainsKey(pattern[i])) { dic.Add(pattern[i], code); str += code.ToString() + "|"; code++; } else { str += dic[pattern[i]].ToString() + "|"; } } return str; } public IList<string> FindAndReplacePattern(string[] words, string pattern) { var pt = ConvertString(pattern); var list = new List<string>(); foreach (var word in words) { var p = ConvertString(word); if (p.Equals(pt)) { list.Add(word); } } return list; } }
原来的实现中没有加"|"对code进行分割,这样的代码也可以ac,但是会有隐藏的bug,那就是如下两个串会得到相同的编码:
abcdefghijklmn
abcdefghijbabbbcbd
两个字符串都会编码为012345678910111213,加了竖线就不会再有这个bug。