Given a string, find the length of the
longest substring
without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given
"pwwkew"
, the answer is
"wke"
, with the length of 3. Note that the answer must be a substring,
"pwke"
is a subsequence and not a substring.
思路1 暴力解法
伪代码:
List<string> sList;
loop(i=0;i<s.Length; i++)
loop(j=i+1; j<s.Length; j++)
sList.Add(GetString(s,i,j)
);
loop(tmpStr in
sList
)
{
remove tmpStr with duplicate char
}
return MaxLength in
sList;
string GetString(string s,int startIndex,int endIndex)
以上思路:超时;
思路2:
想几个例子再跑几遍;用两根指针的思路;
思路:
i - 左指针,负责消除
j - 右指针,负责在map中增加记录
map 用来记录该char是否出现;出现-记录1;否则-记录0;
ans 最长长度;
指针流程,假定输入数组为: abcdcd
1 左指针i(慢指针) 从0循环到最后,最外层循环;
2 右指针(快指针) j从0循环到最后,如果遇到map中没有的记录;执行如下操作
2.1 map中记录该char为1;
2.2 ans取 max(ans,j-i+1),作为最后答案;
2.3 j指针右移一位;直至j指针的char遇到map中有重复元素,就停止;
3 i循环中如果遇到无法进入循环2的。j遇到了重复元素;执行如下操作
3.1 i指针对应char消为0;
3.2 i指针后移;并重复消除;直至消除与j当前重复的元素;
期间,如果发现多个无重复元素的字串,以长度最长的为准,通过Max(x,y)来实现;
C#版本答案:
public int lengthOfLongestSubstring(string s)
{
if (string.IsNullOrEmpty(s))
return 0;
if (s.Length == 1)
return 1;
int[] map = new int[256]; // map from character's ASCII to its last occured index
int j = 0;
int i = 0;
int ans = 0;
for (i = 0; i < s.Length; i++)
{
while (j < s.Length && map[s.ToCharArray()[j]] == 0)
{
map[s.ToCharArray()[j]] = 1;
ans = Math.Max(ans, j - i + 1);
j++;
}
map[s.ToCharArray()[i]] = 0;
}
return ans;
}