- 题目:一个字符串,返回该字符串中最长的连续不重复子串(字符串只包含小写字母)
- 先是按着正常思路撸了个n平方复杂度算法,(边遍历,边比对)
C#
static bool IsDuplicate(string source,char target)
{
for (int i = 0; i < source.Length - 1; i++)
{
if (source[i] == target)
{
return true;
}
}
return false;
}
//n平方算法
public static string GetLongestSubDiffStringNN(string s)
{
if (string.IsNullOrEmpty(s)||s==" ")
{
Console.WriteLine("Empty string!!");
return null;
}
int maxLength = 0, tempLength = 0;
string tempStr = "", maxStr = "";
var chars = s.ToCharArray();
for (int i = 0; i <= chars.Length - 1; i++)
{
//if (IsDuplicate(tempStr, chars[i])
if (tempStr.Contains(chars[i]))
{
tempLength = 1;
tempStr = s[i].ToString();
}
else
{
tempLength++;
tempStr += s[i];
maxStr = tempLength > maxLength ? tempStr : maxStr;
maxLength = tempLength > maxLength ? tempLength : maxLength;
}
}
return maxStr;
}
但是想想n平方复杂度算法是不可容忍的,降低复杂度的重点在于比对是否存在子对象这段逻辑上,于是想说把已存在的字符存在字典里,读取的时候直接拿就好了。
public static string GetLongestSubDiffStringN(string s)
{
if (string.IsNullOrEmpty(s) || s == " ")
{
Console.WriteLine("Empty string!!");
return null;
}
int maxLength = 0, tempLength = 0;
string tempStr = "", maxStr = "";
//用字典存储已存在字符,省去n次的遍历
Dictionary<char, int> haveCharDic = new Dictionary<char, int>();
var chars = s.ToCharArray();
for (int i = 0; i <= chars.Length - 1; i++)
{
if (haveCharDic.ContainsKey(s[i]))
{
tempLength = 1;
tempStr = s[i].ToString();
// 初始化字典
haveCharDic = new Dictionary<char, int>();
haveCharDic[s[i]] = 1;
}
else
{
tempLength++;
tempStr += s[i];
haveCharDic[s[i]] = 1;
maxStr = tempLength > maxLength ? tempStr : maxStr;
maxLength = tempLength > maxLength ? tempLength : maxLength;
}
}
return maxStr;
}