zoukankan      html  css  js  c++  java
  • 3. Longest Substring Without Repeating Characters

    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.

    思路:标记字符串visit[(int)s[i]]=i;

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include<vector>
    using namespace std;
    int maxindex=0;
    class Solution
    {
    public:
    int lengthOfLongestSubstring(string s)
    {
    int len=s.length();
    if(len==0)
    return 0;
    int visit[256];
    memset(visit,-1,sizeof(visit));
    int maxlen=0;
    int curlen=0;
    int last_start=0;
    for(int i=0; i<len; i++)
    {
    if(visit[(int)s[i]]==-1)
    {
    curlen++;
    visit[(int)s[i]]=i;
    }
    else
    {
    if(last_start<=visit[(int)s[i]]) //当前最长串中包括该重复字符s[]
    {
    last_start=visit[(int)s[i]]+1;
    curlen=i-visit[(int)s[i]];
    visit[(int)s[i]]=i;
    }
    else //出现过arr[i]但不在当前最长串中
    {
    curlen++;
    visit[(int)s[i]]=i;
    }
    }
    if(curlen>maxlen)
    {
    maxlen=curlen;
    //maxindex=i+1-maxlen;
    }

    }
    return maxlen;
    }

    };

    int main()
    {
    string s="abcaacdeabacdefg{}dewifh01kw{}";
    Solution sol;
    int i = sol.lengthOfLongestSubstring(s);
    while(i--)
    {
    printf("%c",s[maxindex++]);
    }
    printf(" ");
    }

  • 相关阅读:
    AS出现Connection timed out
    关于eclipse出现The selection cannot be launched,and there are no recent launches
    第十周周赛题解
    FJUT 2401 尼克的任务
    关于3月份的学习总结
    人生的第一题图论
    第六周周赛题解
    Drupal8 社区文档之积极的Drupal版本
    Drupal8 社区文档之Drupal安全吗
    Drupal8 社区文档之技术堆栈
  • 原文地址:https://www.cnblogs.com/dshn/p/7846652.html
Copyright © 2011-2022 走看看