欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

LeetCode 3,LeetCode

来源: javaer 分享于  点击 25265 次 点评:26

LeetCode 3,LeetCode


Longest Substring Without Repeating Characters

 

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.

My Code

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int length = s.length();
        int* longestLengths = new int[length];
        int longestLength = 0, endIndex = 0;
        bool charSet[128] = {0};

        longestLengths[0] = 0;
        for (int i = 0; i < length; i++)
        {
            if (i > 0)
                longestLengths[i] = longestLengths[i-1] - 1;

            for (int j = endIndex; j < length; j++)
            {
                // The character is already in the set
                if (charSet[s[j]] == true)
                {
                    endIndex = j;
                    charSet[s[i]] = false;
                    if (longestLength < longestLengths[i])
                        longestLength = longestLengths[i];
                    break;
                }
                else
                {
                    charSet[s[j]] = true;
                    longestLengths[i]++;

                    // The character is the last character of the string
                    if (j == length - 1)
                    {
                        if (longestLength < longestLengths[i])
                            longestLength = longestLengths[i];
                        return longestLength;
                    }
                }
            }
        }

        return longestLength;
    }
};
Runtime: 16 ms

相关文章

    暂无相关文章

用户点评