难度:MEdium
描述:
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.
原题要你找出字符串中包含不重复字符的最长字串的长度
我们可以用一个max变量来记录已经找到的最长子串的长度,然后用一个临时字符串来加入字符记录子串,一旦发现有重复的字符,就把这个临时字符串长度同max对比,然后把临时字符串中重复字符之前的部分去掉(包括重复字符自己),再加入这个新的字符,最后要把max和临时字符串的长度对比,选最大的返回
代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.length() == 0) return 0;
int max = 1;
string cur;
cur += s[0];
for (int i = 1; i < s.length(); i++) {
if (cur.find(s[i]) == string::npos) {
cur += s[i];
} else {
if (max < cur.length()) max = cur.length();
cur = cur.substr(cur.find(s[i])+1);
cur += s[i];
}
}
if (cur.length() > max) {
return cur.length();
} else {
return max;
}
}
};
本文介绍了一种求解字符串中最长无重复字符子串长度的方法。通过使用一个临时字符串来记录当前子串,并在遇到重复字符时更新最长子串长度。
686

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



