LeetCode 3. Longest Substring Without Repeating

本文介绍了一种算法,用于解决字符串中无重复字符最长子串的问题,通过使用哈希映射和双指针技巧,实现高效求解。

 

题目:

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.

 

思路:

用一个map存放字符出现的position;用两个指针begin,end指向substr的首末;遇到相同字符时将begin移到该字符之前出现的后一位置,并更新该字符的position。

 

代码:C++ :

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.length() <= 1)
            return s.length();
        
        int begin = 0;
        int end = 0;
        map<char,int> mapping;
        int solve = 0;
        
        mapping[s[0]] = 0;
        while (end < s.length() - 1) {
            end++;
           if (mapping.find(s[end]) != mapping.end()) {
                int gap = end - begin;
                if (gap > solve)
                    solve = gap;
                begin = mapping[s[end]] + 1 > begin ? mapping[s[end]] + 1 : begin;
                mapping[s[end]] = end;
            }
            else
                mapping[s[end]] = end;
        }
        int gap = end - begin + 1;
        if (gap > solve)
            solve = gap;
        return solve;
    }
};

 

Reference : https://leetcode.com/discuss/59051/c-code-in-9-lines

本质上跟我的思路差不多,但是代码很简洁

int lengthOfLongestSubstring(string s) {
        vector<int> dict(256, -1);
        int maxLen = 0, start = -1;
        for (int i = 0; i != s.length(); i++) {
            if (dict[s[i]] > start)
                start = dict[s[i]];
            dict[s[i]] = i;
            maxLen = max(maxLen, i - start);
        }
        return maxLen;
    }

由此可知:

dict['A']与dict[65]等效,即与ASCII码对应

转载于:https://www.cnblogs.com/gavinxing/p/5186141.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值