3. Longest Substring Without Repeating Characters

来源:互联网 发布:淘宝客机器人有哪些 编辑:程序博客网 时间:2024/05/18 22:42

题目:

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 asubstring,"pwke" is a subsequence and not a substring.

思路:

思路借鉴别人的思路,目的是要寻找最长子串,且子串没有任何两两相等的字符。

        用字符数组进行存储,当遇到字符串中的字符a,则用如ch[‘a’]++表示字符中有一个'a'。一旦ch['a']的值大于1,则表示当前字符串中已经有重复字符了,不需要再继续了。

只要ch['字符串中的字符']没有大于1,就表示没有重复则,继续向后探索。

        探索路线就是从字符串的第一个字符开始,如果没有遇到重复字符就一直往后,遇到就终止,比较当前长度和最大长度,判断是否需要对最大长度重赋值;

接着从第二个字符开始按相应规则探索。

        因此,用两个循环。

代码:


int lengthOfLongestSubstring(char* s) {    char ch[256]={'\0'}; //={'\0'};后者用memset两者进行初始化都行    //memset(ch,0,256); //sizeof(ch)是256        int i=0,j=0;    int maxlen=0,newlen=0;        for(i=0;s[i]!='\0';i++)    {        for(j=i;s[j]!='\0';j++)        {            int tmp=s[j];             ch[tmp]++;            //每个字符不能重复            if(ch[tmp]>1)            {                newlen=j-i;                memset(ch,0,256);//恢复为0                break;            }        }        if(s[j]=='\0')        {            newlen=j-i;        }                if(newlen>maxlen)        {            maxlen=newlen;        }    }    return maxlen;}



















0 0
原创粉丝点击