LeetCode-Longest Substring Without Repeating Characters

问题描述:求一个字符串中的最大不重复子串

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.

原题地址:https://leetcode.com/problems/longest-substring-without-repeating-characters/

关于字符串的比较经典的问题,网上可以搜到很多解法,博主在论坛里找到一个最简洁的方法,且时间复杂度仅为o(n)。该算法比较另类,主要是通过一个256维的一维数组来实现的。核心思想是把字符串中的字符映射到上述一维数组中,然后通过移动lastrepeatpos来处理有重复字符的情况。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int m[256];
        fill(m, m+256, -1);
        int maxLen = 0, lastRepeatPos = -1;
        for(int i=0; i<s.size(); i++) {
            //重复的位置必须要小于当前字符的位置才移动lastrepeatpos
            if (m[s[i]]!=-1  && lastRepeatPos < m[s[i]] ) 
               lastRepeatPos = m[s[i]];
            //更新计算最大不重复字符串的长度
            if ( i - lastRepeatPos > maxLen ) 
               maxLen = i - lastRepeatPos;
               m[s[i]] = i;
        }
        return maxLen;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值