Longest Substring Without Repeating Characters

来源:互联网 发布:linux安装mysql源码包 编辑:程序博客网 时间:2024/06/04 19:10

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.

Subscribe to see which companies asked this question.

class Solution {public:    int lengthOfLongestSubstring(string s) {   //考虑大写字符        int len = s.length();        if(len == 0)            return 0;//pos[]存储每个字符最新出现的位置,curi和curj表示当前没有重复字符区间,posi和posj表示最长的没有重复字符的区间        int pos[200], curi, curj, posi, posj, i;             for(i = 0; i < 200; i++)            pos[i] = -1;        curi = 0;        curj = 0;        posi = 0;        posj = 0;        pos[s[0]] = 0;        for(i = 1; i< len; i++){            if(pos[s[i]] < curi){      //该字符未在当前区间出现过                curj = i;            }else if((curj - curi) > (posj - posi)){  //当前字符在当前区间出现过,且当前区间的长度大于之前的最长区间                posi = curi;      //更新最长区间                posj = curj;                curi = pos[s[i]] + 1;   //更新当前区间                curj = i;            }else{      //当前字符在当前区间出现过,且当前区间的长度小于之前的最长区间                curi = pos[s[i]] + 1;    //更新当前区间                curj = i;            }            pos[s[i]] = i;   //更新当前字符的最新位置        }        if((curj - curi) > (posj - posi)){    //跳出循环后判断当前区间是否大于之前的最长区间            posi = curi;            posj = curj;        }        return posj - posi + 1;    }};


0 0