leetcode——Longest Substring Without Repeating Characters 求链表中无重复字符的最大字串长度(AC)

来源:互联网 发布:电脑优化提速 编辑:程序博客网 时间:2024/06/15 22:10

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

为了提升时间效率,我开辟了一个长度为256的整型数组来标识子串中的字符是否重复,避免了采用循环比较的方法来判定字符是否重复。需要注意的是当我们发现一个字符与当前子串中的字符重复时,此时新的字串需要从子串中第一次出现此字符位置的后一个字符开始作为新的子串的起点,代码中采用了一个整型变量来记录判定过程中的最大子串长度。代码如下:

class Solution {public:    int lengthOfLongestSubstring(string s) {        int length = s.length(),maxValue=0,count=0;int flag[256];Reset(flag);for(int i=0; i<length; i++){if(flag[s[i]] == -1){count++;flag[s[i]] = i;}else {i = flag[s[i]]+1;Reset(flag);flag[s[i]] = i;count=1;}if(maxValue < count)maxValue = count;}return maxValue;    }void Reset(int *flag){for(int i = 0; i<256; i++)flag[i] = -1;}};


0 0