LeetCode 03-無重複字元的最長子串
阿新 • • 發佈:2018-12-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; } };