leetcode medium: 3. 无重复字符的最长子串[字符串]

题很简单,就是求解一个字符串中无重复的最长连续子串。

需要两个指针,一个start_idx:记录当前无重复子串的最左端索引;一个i,记录当前所处的字符索引。

maps记录当前无重复子串中各字符出现的次数,如果maps['a']=1,则表示该子串中a出现过一次。无重复子串即表示maps中所有字符的映射值均<=1。

每次i往右移动一次,当前字符为ch,则maps[ch]++。如果maps[ch]>1,则表示此前ch已经出现过一次,需要将start_idx也开始往右移动,同时将经过的字符从maps清除出去。直到start_idx到达i或者说maps[ch]<=1。

如果maps[ch]=1,那符合条件,此时无重复子串的长度为i - start_idx + 1,和ans取max即可。

AC结果:

Runtime: 20 ms, faster than 65.81% of C++ online submissions for Longest Substring Without Repeating Characters.

Memory Usage: 8.5 MB, less than 66.56% of C++ online submissions for Longest Substring Without Repeating Characters.

#include <iostream>
#include <algorithm>
#include <string.h>
#include <vector>
#include <map>
#include <stdio.h>
using namespace std;
const int maxn = 50000+5;
//char s[maxn];
string s;

int lengthOfLongestSubstring(string s) {
    int len = s.length();
    if(!len)
        return 0;
    map<char,int> maps;
    maps[s[0]]=1;
    int ans = 1;
    int start_idx = 0;
    for(int i=1;i<len;i++){
        maps[s[i]]++;
        if(maps[s[i]]>1){
            while(start_idx<i && maps[s[i]]>1){
                maps[s[start_idx]]--;
                start_idx++;
            }
        }
        else{
            ans=max(i-start_idx+1, ans);
        }
    }
    return ans;
}

int main()
{
    string s = "abcabcbb";
    int ans = lengthOfLongestSubstring(s);
    cout<<ans<<endl;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值