LeetCode#3* Longest Substring Without Repeating Characters

本文介绍了一种求解最长无重复子串长度的问题,并提供了一个C++实现方案。通过使用数组记录字符出现的位置,算法能有效避免重复字符并更新最长子串长度。

题目:Given a string, find the length of the longest substring without repeating characters.

Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

       题意:就是寻找一个给定字符串中的不重复最长字串的长度。比如abcdab,最长的串位abcd或cdab,长度位4.
        这道题中,首先,想到是字符串,然后就可以想到用255大小的桶来标记下标对应的字母是否出现过,即cnt[255],然后想到用hash表,用一个hash table保存每个字符上一次出现过的位置,即vis[255]。从前往后扫描,假如发现字符上次出现过,就把当前子串的起始位置start移动到上次出现过的位置之后——这是为了保证从start到i的当前子串中没有任何重复字符。同时,由于start移动,当前子串的内容改变,start移动过程中经历的字符都要剔除。

class Solution {
public:
    int max(int a,int b)
    {
        return a>b?a:b;
    }
    int lengthOfLongestSubstring(string s) {
        int len=s.length();
        int cnt[256]={0};
        int vis[256]={0};
        int i,j;
        int start=0;
        int Max=0;
        for(i=0;i<len;i++)
        {
            if(!cnt[s[i]])
            {
                cnt[s[i]]=1;
                vis[s[i]]=i;
                Max=max(Max,i-start+1);
            }
            else 
            {
                Max=max(Max,i-vis[s[i]]);
                for(j=start;j<=vis[s[i]];j++)
                {
                    cnt[s[j]]=0;
                }
                start=vis[s[i]]+1;
                vis[s[i]]=i;
                cnt[s[i]]=1;
            }
        }
        return Max;
    }
};

这次排名相当不错啊

排名

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值