Leetcode Longest Substring Without Repeating Characters

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


问题:思路2在java下可以Leetcode AC,但是在C#版本下,一直提示超时;无法AC;很困惑
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值