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.
题意在原串中找到最长的每个字母最多出现一次的字符串
用一个sign[256]来记录出现过的字符位置,偷懒点用265可以处理一个ASCII表。
遇到没有出现过的字符,将sign对应位置标记-1。
遇到出现过的字符,出现该字符上次出现位置前面截断(即赋值为-1),调整长度。
#include<iostream>
#include <algorithm>
#include<cstring>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int start = 0;
int movep = 0;
int sign[256];
int mmax = 0;
int templen = 0;
int curStart = 0;
int lastSi = 0;
memset(sign,-1,sizeof(sign)); //注意mem第三个参数,类型是size_t
for(;movep<s.size();movep++)
{
char si = s[movep];
lastSi = sign[si];
if( sign[si] == -1)
{
templen++;
sign[si] = movep;
}
else
{
//删除前面重复的,重新调整长度
curStart = movep - templen;
for(int j = curStart; j < lastSi; ++j) {
sign[s[j]] = -1;
}
templen = movep - lastSi;
sign[si] = movep;
}
mmax = max(mmax,templen);
}
return mmax;
}
};
本文介绍了一种算法,用于在给定字符串中找到最长的子串,其中每个字符只出现一次。通过使用一个数组记录字符的位置,该算法能够高效地解决此问题。
965

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



