原题
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.
代码实现
public int LengthOfLongestSubstring(string s)
{
//first it must be substring: that's a continuous interval for s
StringBuilder sb = new StringBuilder();
int max = 0, curmax=0;
for (int i = 0; i < s.Length; i++)
{
string substr = sb.ToString();
int ind = substr.IndexOf(s[i].ToString(), StringComparison.Ordinal);
if(ind==-1)//no containing s[i]
{
sb.Append(s[i]);
curmax++;
}
else
{
if (max < curmax) max = curmax;
//This block especially solves the string like that "abcabc..." , or it would exceed time
if (s.Substring(i).IndexOf(substr, StringComparison.Ordinal) != -1)
{
i += substr.Length-1;
continue;
}
// i - substr.Length: start index for substr
// i - substr.Length + ind: moves ind numbers
i = i - substr.Length + ind;
sb.Clear();
curmax = 0;
}
}
if (max < curmax) max = curmax;
return max;
}
**还有一种更简洁高效的算法,如下所示,代码中做了详细文字说明。
public int LengthOfLongestSubstring(string s)
{
int[] arr = new int[256];
//why is 255? because 255 describes all ASCII char
//每个符号取值初始化都为-1,表示这个字符还未出现
for (int i = 0; i <= 255; i++)
{
arr[i] = -1;
}
int maxLen = 0, start = -1;
for (int i = 0; i != s.Length; i++)
{
int ch2int = Convert.ToInt32(s[i]);
if (arr[ch2int] > start) //表示这个字符已经出现,也就是重复
start = arr[ch2int]; //修改新一轮字符串的起始位置
arr[ch2int] = i; //不断刷新arr
maxLen = Math.Max(maxLen, i - start); //i-start:当前字符串的长度
}
return maxLen;
}
题库
Leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp