题目:
Find first repeating letter in a string.
比如输入“abcba”, 返回“a”
思路1:
找出第1个元素,然后判断剩下的字符串是否包含第1个元素;
找到第2个元素,然后判断剩下的字符串是否包含第2个元素;
以此类推……
有则返回charArray[i]
时间复杂度:O(N^2)
C#代码:
public static char FirstRepeatingLetter(string str)
{
char[] charArray = str.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
int j = i + 1;
if (str.Substring(j).Contains(charArray[i]))
return charArray[i];
}
return new Char();
}
思路2(优化后)
时间复杂度:O(N)
利用HashMap/Dictionary
1 先统计所有的频率,O(N)
2 找出Value(频率)大于1的Key
C#代码:
public static char FirstRepeatingLetter(string str)
{
Dictionary<char, int> charFrequencyDic = new Dictionary<char, int>();
char[] charArray = str.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
if(!charFrequencyDic.ContainsKey(charArray[i]))
charFrequencyDic.Add(charArray[i],1);
else
charFrequencyDic[charArray[i]]+=1;
}
var query = charFrequencyDic.Where(r => r.Value > 1).Select(r => r.Key);
if (query.Any())
return query.First();
else
return new Char();
}