问题描述
简单来说,就是找一个字符串中最长的不存在重复字母的子串长度
自然遍历字符串一遍是不可避免的,自然,我的想法就是建立一个临时字符串变量temp存储当前遍历到的无重复字母的字符串,在对给定字符串进行遍历的时候,可能会出现几种情况:
- 不是重复字母,则temp将其加上
- 是重复字母,则:
a. 首先比较当前temp长度和目前所遇到的最长长度哪个大,若是temp较长则替换
b. 如果重复字母出现在temp的中间,则中间及以前的字符串都必须剔除,新的temp是重复字母之后的子串与重复字母的合
c. 如果重复字母出现在末位,则temp元素全部替换
下面是源代码:
int lengthOfLongestSubstring(string s) {
string temp;
int biggestLength = 0;
size_t pos;
for (int i = 0; i < s.size(); i++) {
pos = temp.find(s[i]);
if (pos != string::npos) {
if (temp.size() > biggestLength)
biggestLength = temp.size();
/* The repeating character isn't in the end of the string "answer" */
if (pos != temp.size() - 1) {
temp = temp.substr(pos + 1) + s[i];
} else {
temp = s[i];
}
} else {
temp += s[i];
}
}
if (temp.size() > biggestLength)
biggestLength = temp.size();
return biggestLength;
}
时间复杂度是O(n),暂且没有找到更好的办法,希望能获取大家的建议