题目:给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度
示例1:
输入: s = “abcbcabd”
长度: 4
无重复字符的最长子串是 “cabd”,其长度为 4。
示例2:
输入: s = “pwwkew”
长度: 3
无重复字符的最长子串是 “kew”,其长度为 3。
代码实现
Lua
function this:LengthOfLongestSubstring(str)
local table = {}
for i = 1, string.len(str) do
local s = string.sub(str,i,i)
table[i] = s --字符串转有序列表
end
local dic = {}
local max = 0
for i = 1, #table do
if dic[table[i]] then dic = {} end --包含重复的键则清空表
dic[table[i]] = true
local count = 0
for _, _ in pairs(dic) do
count = count + 1 --计算表长
end
max = count > max and count or max
end
return max
end
C#
//方法1:索引
public int LengthOfLongestSubstring(string s)
{
List<char> ls = new List<char>();
int len = s.Length;
int maxLength = 0;
for (int i = 0; i < len; i++)
{
if (ls.Contains(s[i]))
{
ls.RemoveRange(0, ls.IndexOf(s[i]) + 1);
}
ls.Add(s[i]);
maxLength = ls.Count > maxLength? ls.Count : maxLength;
}
return maxLength;
}
//方法2:滑动窗口
public int LengthOfLongestSubstring(string s)
{
HashSet<char> letter = new HashSet<char>();
int left = 0; int right = 0;//初始化左右两个指针,指向字符串首字母
int maxLength = 0; int count = 0;
while (right < s.Length)
{
if (!letter.Contains(s[right]))//右指针未重复,继续往前
{
letter.Add(s[right]);
right++;
count++;
}
else//右指针重复,原地不动,左指针往前,移除元素
{
letter.Remove(s[left]);
left++;
count--;
}
maxLength = count > maxLength? count : maxLength;
}
return maxLength;
}