最长的无重复字符的字符串 longest substring with no repeating characters

来源:互联网 发布:信捷plc编程案例 编辑:程序博客网 时间:2024/06/11 13:31

相关问题:[LeetCode] minimum window 包含所有字符的最小子字符串

Given a string, find the length of the longest substring without repeating characters. For example,the longest substrings without repeating characters for “ABDEFGABEF” are “BDEFGA” and “DEFGAB”, with length 6. For “BBBB” the longest substring is “B”, with length 1. For “GEEKSFORGEEKS”, there are two longest substrings shown in the below diagrams, with length 7.



The desired time complexity is O(n) where n is the length of the string.

自己的算法如下,思路可以参考http://www.geeksforgeeks.org/length-of-the-longest-substring-without-repeating-characters/:

#include<iostream>#include<stdio.h>#include<stdlib.h>using namespace std;#include <string.h>#include <set>int main (){        set<char> str_set;        char * str = "ABDEFGABEFFFFFFFFFFFF";        str_set.insert(*str);                int n = strlen(str);        int i=0, j=1;        int max_ = 0;        while(1)        {                for(; j<n; j++)                {                        if(str_set.find(*(str+j) )!=str_set.end())                                break;                        str_set.insert(*(str+j));                        max_ = max(max_, (int) str_set.size() );                }                if(j==n-1)                        break;                for(; i<n; i++)                {                        str_set.erase( *(str+i) );                        if( *(str+j) == *(str+i) )                        {                                i++;                                break;                        }                }        }        cout<<max_<<endl;}


0 0
原创粉丝点击