【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.

我的解题思路:
这个问题比较像之前写过的博客《【July程序员编程艺术】之最大字段和问题》,所以决定采用跟最大字段和一样的算法来解决这个问题:即使用hash表,在O(N)的时间内求解这个问题。
从最后一个字符开始,遍历整个字符串。每次循环都维护从当前字符开始的最长的子串的idx和实际长度,每新来一个字符,首先判断其是否出现于子串,如果没有则好办,直接将其与子串拼接。如果有,则需要修改相应子串的长度和idx,最后提交通过的程序如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
         map<char, int> hash_map;
        int len = s.length();
        if(len==0)
            return 0;
        int idx = len-1;
        hash_map[s[len-1]]=idx;
        int idx_max=len-1;
        int tmp_max = 1;
        int total_max=1;
        if(len==1)
            return 1;
        for(int i=len-2;i>=0;i--)  //substring start from i
        {
            char curr_st = s[i];
            if(hash_map[curr_st]<=0)
            {
                hash_map[curr_st]=i;
                tmp_max++;
                if(tmp_max>total_max)
                    total_max=tmp_max;
            }
            else
            {
                if(idx_max>=hash_map[curr_st])
                {
                tmp_max=hash_map[curr_st]-i;
                idx_max=hash_map[curr_st]-1;
                hash_map[curr_st]=i;

                if(tmp_max>total_max)
                    total_max=tmp_max;
                }
                else
                {
                      hash_map[curr_st]=i;
                        tmp_max++;
                        if(tmp_max>total_max)
                            total_max=tmp_max;
                }

            }



        }
        return total_max;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值