[LeetCode] Longest Substring Without Repeating Characters [15]

题目

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

原题链接

解题思路

求解字符串中无重复元素的最长子串。解决本题的方法是记住当前元素在这之前最后一次出现的位置。具体请参考代码中的注释。

代码实现

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.size();
        if(n<=0)  return 0;
        // 记录字符最后一次出现的位置
        int table[256];
        for(int i=0;i<256; ++i)
            table[i] = -1;
        int max = 0;
        int RepeatIndex = -1;
        for(int i=0; i<n; ++i){
            //该字符在 i 和 RepeatIndex之间出现过,则更新RepeatIndex
            if(table[s[i]] > RepeatIndex){
                RepeatIndex = table[s[i]];
            }
            int len = i-RepeatIndex;
            if(len > max)  max = len;
            table[s[i]] = i;
        }
        return max;
    }
};

如果你觉得本篇对你有收获,请帮顶。
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你可以搜索公众号: swalge  或者扫描下方二维码关注我

(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/29185691 )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值