c# - 我是否将滑动窗口增加得太远了?
问题描述
我正在努力解决LeetCode 上的这个问题,它找到给定字符串的最长子字符串而不重复字符。我的解决方案适用于某些字符串(例如'pwwkew'),但不适用于其他字符串(例如'ckilbkd')。有什么建议么?
public int LengthOfLongestSubstring(string s) {
if (s.Length < 2) return s.Length;
HashSet<char> existing = new HashSet<char>();
Stack<string> vals = new Stack<string>();
int start = 0;
int end = 1;
int result = 1;
existing.Add(s[0]);
while (end < s.Length && start < end)
{
if (!existing.Contains(s[end]))
{
if (end == (s.Length - 1))
{
result = s.Length - start;
Console.WriteLine("here");
break;
}
existing.Add(s[end]);
end++;
}
else
{
var res = s.Substring(start, end - start);
if (vals.Count == 0)
{
vals.Push(res);
result = res.Length;
}
else if (res.Length > vals.Peek().Length)
{
vals.Pop();
vals.Push(res);
result = res.Length;
}
if (s[end] == s[end - 1])
{
start = end;
end++;
}
else
start++;
}
}
return result;
}
解决方案
推荐阅读
- c# - SqlDataReader 结果到列表
- php - 如何使用 wamp64 连接到 MSSQL DB
- powershell - 在 powershell 命令中使用通配符批量重命名多个文件
- php - 未捕获的错误:找不到类“文档”
- perl - 正则表达式将 JSDoc 从咖啡脚本转换为 javascript
- python - 正则表达式:匹配重复(任意时间)模式,但在不同的组中排序
- angular - 如何在按钮单击时更改激活路由的参数
- jmeter - JMeter:要报告的用户变量
- javascript - 如何单独监听 x 滚动和 y 滚动的滚动事件
- java - JavaFXML + Scenebuilder:LineChart 未显示值