Leetcode-不重复的最长字符串

算法和数据结构什么时候学什么时候新,做过的题再刷的时候感觉还是新的

下边这道题原题链接如下

longest-substring-without-repeating-characters

Given a string s, find the length of the longest 

substring

 without repeating characters.

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
int lengthOfLongestSubstring(char* s) {
    if(s == NULL || strlen(s) == 0 )
    {
        return 0;
    }
    int array[256] = {-1};//用于记录字符第一次出现的位置
    int length = strlen(s);//获取s的长度
    int StartL = 0;//从0长度开始遍历
    int maxLength = 1;//默认长度为1
    for (int i = 0; i < 256; i++) {
        array[i] = -1;//初始化array记录为-1(未发现数据)
    }
    for (int i = 0; i < length; i++) {

        if(array[s[i]] >= StartL)//如果该字符所在的位置在STARTL右方(包含STARTL位置),说明该字符在STARTL-I区间出现过
//为什么有这个判断:防止该字符在STARTL之前出现过
        {
            //更新长度
            maxLength = maxLength > (i -StartL)?maxLength:(i -StartL);
            //更新STARTL位置,向后移动一位
            StartL = array[s[i]]+1;
        }
        //更新该字符所在位置
        array[s[i]] = i;
    }
//for跑出来之后再计算一下最后一个字符到STARTL的位置
    maxLength = maxLength > (length -StartL)?maxLength:(length-StartL);


    return maxLength;
}

你可能感兴趣的:(leetcode,java,算法)