LeetCode | Longest Substring Without Repeating Characters

来源:互联网 发布:怎么在电脑上登录淘宝 编辑:程序博客网 时间:2024/06/04 18:07

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.

求一个字符串的最长不重复子串,
一开始写的双循环

显然包含了很多重复计算,例如i~j如果包含两个相等的字符,那么i~j一定不是所要找的串。
于是可以另开一个指针,如果遇到的元素之前没有遇到,那么就记录到数组里,否则,更新最长距离,并修正最大节点的起始点。
这个图片很是棒,很好地说明了问题,即每次遇到相同的字符的时候,起始位置为相同字符的位置+1;
pic

class Solution {public:    int lengthOfLongestSubstring(string s) {        int n=s.size(),max=0,start=-1;        int a[256];        for(int i=0;i<256;i++) a[i]=-1;        for(int i=0;i<n;i++){            //start用于记录开始字符            //通过这个判断,表示之前出现过相应的字符            //更新出发点            if(a[s[i]]>start)                start=a[s[i]];            a[s[i]]=i;            max=max >= (i-start)?max:(i-start);            // int pos=i;            // char a[128];            // memset(a,0,sizeof(a));            // a[s[i]]=1;            // for(int j=i+1;j<n;j++){            //     if(a[s[j]]>0) break;            //     else{ pos=j;a[s[j]]=1;}            // }            // if(pos-i+1>max)            // max=pos-i+1;        }        return max;    }};
0 0
原创粉丝点击