LeetCode 03-无重复字符的最长子串

C版本1 

int getmax(int a,int b);
int lengthOfLongestSubstring(char* s) {
    int nowlength=0,maxlength=0;
    int i,j;
    int begini=0,endi=0;
    
    while(s[endi]!=NULL&&s[endi+1]!=NULL)
	{
		i=endi+1;//i是要新加入的
		for(j=begini;j<=endi&&s[j]!=s[i];j++);
		if((j <= endi) && s[j]==s[i])//出现重复
		{
			nowlength = endi-begini+1;
			maxlength=getmax(nowlength,maxlength);
			begini=j+1;
			endi=endi+1;
		}
		else//没有重复,长度扩展
		{
			endi = endi +1;
		}
		 
    }
    if(s[endi]==s[begini-1])
    {}
    else{
        nowlength = endi-begini+1;
	    maxlength=getmax(nowlength,maxlength);
    }
    
    
    
    return maxlength;
}
int getmax(int a,int b)
{
    return (a>b?a:b);
}

C版本2

int lengthOfLongestSubstring(char* s) {
     if (strlen(s) <= 1)
        return strlen(s);//只有一个字符的情况
    int len = 1;//超过一个字符,最短长度为1
    char * pStart = s;//子串的开始元素(包含)
    char * pEnd = s + 1;//子串的结束元素的下一位(不包含)
    for (; *pEnd != '\0'; ++pEnd)
    {
        int count = 0;
        char * pTmp = pStart;
        for (; pTmp != pEnd; ++pTmp)
        {
            if (*pEnd == *pTmp)
            {
                pStart = pTmp + 1;
                break;
            }
            else
            {
                ++count;
                continue;
            }
        }
        if (pTmp == pEnd)
        {
            ++count;
            if (len < count)
                len = count;
        }
    }
    return len;
}

C++版本

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int m[256] = {0}, res = 0, left = 0;
        for (int i = 0; i < s.size(); ++i) {
            if (m[s[i]] == 0 || m[s[i]] < left) {
                res = max(res, i - left + 1);
            } else {
                left = m[s[i]];
            }
            m[s[i]] = i + 1;
        }
        return res;
    
    }
};

猜你喜欢

转载自blog.csdn.net/tingfenghanlei/article/details/83829682