Longest Substring Without Repeating Characters
Medium
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"Output: 3
Explanation: 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 static int LengthOfLongestSubstring(string s)
{
string newstr = string.Empty;
int maxlen = 0;
foreach (char item in s)
{
if (newstr.Contains(item))
{
int index = newstr.IndexOf(item);
if (newstr.Length > index + 1)
newstr = newstr.Substring(index + 1, newstr.Length - index - 1);
else
newstr = string.Empty;
}
newstr+=item;
maxlen = newstr.Length > maxlen ? newstr.Length : maxlen;
}
return maxlen;
}
审题审错了,因为题目下面列的太有诱导性了,Given a string, find the length of the longest substring without repeating characters.我理解成"获取一个字符串中最长的连续字符串",其实只要筛选出字符串不重复的长度就行了。而且,我用c#写的代码,
运行时间居然能超过60%,可以理解用c#的人太少了,又或者是LeetCode上面用的是Mono?其实这也是Microsoft遗留的历史问题了,你不能跨平台,人家肯定用Mono啦,那么时间用了92ms,内存用了24M,果断在本地用VS算一下时间和内存,才4ms,10MB。
因为字符串装箱拆箱太频繁了,用前后指针来计算字符串长度并且用哈希表存储当前对应的长度。(LeetCode叫这种方法Sliding window,让我想起来TCP、IP那个停止等待的滑动窗口处理办法,果然基础要学得好,才会再其他方面一通百通)
public static int LengthOfLongestSubstring4(string s)
{
int n = s.Length, ans = 0;
Hashtable map = new Hashtable();
for (int j = 0, i = 0; j < n; j++)
{
if (map.Contains(s[j]))
i = Math.Max((int)map[s[j]], i);
ans = Math.Max(ans, j - i + 1);
map[s[j]] = j + 1;
}
return ans;
}
看到上面还有一种终极算法,因为用哈希表还是太耗时间内存了,如果我们用更简单的方法--数组来提替换HashTable,但是得提前知道字符串的大小。
public static int LengthOfLongestSubstring(string s)
{
int n = s.Length, ans = 0;
int[] arrays = new int[128];
for (int j = 0, i = 0; j < n; j++)
{
i = Math.Max(arrays[s[j]],i);
ans = Math.Max(ans, j - i + 1);
arrays[s[j]] = j + 1;
}
return ans;
}