LeetCode:Longest Substring Without Repeating Characters

 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;
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值