TypechoJoeTheme

IT技术分享

统计

[LeetCode 3] Longest Substring Without Repeating Characters [C] [Runtime : 18 MS]

2017-04-28
/
0 评论
/
529 阅读
/
正在检测是否收录...
04/28

1. Description

Given a string, find the length of the longest substring without repeating characters.

2. Example

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.

3. Code

int lengthOfLongestSubstring(char* s)
{
    int mAscii[256] = { 0 }, mResultLength = 0, i = 0;

    while (s[i] != '\0')
    {
        if (!mAscii[s[i]])
        {
            mAscii[s[i++]] ++;
            continue;
        }
        if(mResultLength < i)
        {
            mResultLength = i;
        }
        while (s[0] != s[i])
        {
            mAscii[s[0]] --;
            s++;
            i--;
        }
        s++;
    }
    if (s[i] == '\0' && mResultLength < i)
    {
        mResultLength = i;
    }

    return mResultLength;
}
#include<stdio.h>

int lengthOfLongestSubstring(char* s)
{
    int mAscii[256] = { 0 }, mResultLength = 0, i = 0;
    char *mResult = s;

    while (s[i] != '\0')
    {
        if (!mAscii[s[i]]) {
            mAscii[s[i++]] ++;
            continue;
        }
        if(mResultLength < i)
        {
            mResult = s;
            mResultLength = i;
        }
        while (s[0] != s[i])
        {
            mAscii[s[0]] --;
            s++;
            i--;
        }
        s++;
    }
    if (s[i] == '\0' && mResultLength < i) {
        mResult = s;
        mResultLength = i;
    }

    for (int i = 0; i < mResultLength; i++) {
        printf("%c ", mResult[i]);
    }
    printf("\n%d\n", mResultLength);

    return mResultLength;
}

int main()
{
    char s[9] = { 'a','b','c','a','b','c','b','b','\0' };
    lengthOfLongestSubstring(s);
    system("pause");
    return 0;
}

4. Submission Details

5. Runtime Distribution

Array
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/94/(转载时请注明本文出处及文章链接)