Given a string, find the length of the longest substring without repeating characters.
Examples:
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.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.empty() || (0 == s.size()))
{
return 0;
}
char T[256] = {0};
char T1[256] = {0};
int mxl = 0;
int lastMxl = 0;
for (int i = 0; i < s.size(); i++)
{
int index = s[i];
if (T[index] > 0)
{
int pos = T[index];
for (int j = 0; j < mxl; j++)
{
int tmp = T[T1[j]] - pos;
T[T1[j]] = (tmp <= 0) ? 0 : tmp;
}
for (int j = 0; j < mxl; j++)
{
if ((pos + j) < 256)
{
T1[j] = T1[pos + j];
}
else
{
T1[j] = '\0';
}
}
if (mxl > lastMxl)
{
lastMxl = mxl;
}
mxl = mxl - pos;
}
T1[mxl++] = s[i];
T[index] = mxl;
}
return (mxl > lastMxl) ? mxl : lastMxl;
}
};
本文介绍了一种解决字符串中寻找最长无重复字符子串问题的算法实现。通过使用两个辅助数组来跟踪字符的位置和有效性,该方法能够在遍历字符串的同时更新最长子串的长度。适用于需要高效查找最长无重复子串的应用场景。
977

被折叠的 条评论
为什么被折叠?



