最长无重复字符的子串-LintCode

本文介绍了一种求解字符串中最长无重复字符子串的高效算法,通过一次遍历结合哈希表记录字符位置,实现O(n)的时间复杂度。适用于编程面试和技术挑战。

给定一个字符串,请找出其中无重复字符的最长子字符串。

样例:
例如,在”abcabcbb”中,其无重复字符的最长子字符串是”abc”,其长度为 3。
对于,”bbbbb”,其无重复字符的最长子字符串为”b”,长度为1。

挑战 :
O(n) 时间

思路:
遍历字符串,对于每个字符计算长度和起始位置,若在已遍历的字符串中不存在,则起始位置不变,直接计算长度;若在已遍历的字符串中存在,更新起始位置,计算长度,最终取最大长度。

#ifndef C384_H
#define C384_H
#include<iostream>
#include<vector>
#include<map>
using namespace std;
class Solution {
public:
    /*
    * @param s: a string
    * @return: an integer
    */
    int lengthOfLongestSubstring(string &s) {
        // write your code here
        if (s.empty())
            return 0;
        int res = 0;
        int start = 0;
        map<char, int> m;
        for (int i = 0; i < s.size();++i)
        {
            if (m.find(s[i]) == m.end())
            {
                m[s[i]] = i;
            }
            else
            {
                start = maxVal(m.find(s[i])->second+1,start);   
                m.find(s[i])->second = i;
            }
            res = maxVal(res, i - start + 1);
        }
        return res;
    }
    int maxVal(int a, int b)
    {
        return a > b ? a : b;
    }
};
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值