您的位置:首页 > 编程语言 > C语言/C++

LeetCode之3_Longest Substring Without Repeating Characters

2016-04-04 18:07 323 查看
题目原文:

 

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.

Subscribe to see which companies asked this question
 

分析:输入一个字符串,找到其中最长的不包含重复字符的字串,并返回其长度。

          暴力解法,将字符放入一个队列当中,每次有新的字符加入时,从队列中查找该字符是否已经出现过。若出现过,则弹出上一次出现的字符及其之前加入队列的所以字符,并计算当前的字串长度,最后返回最长的字串长度。

 

代码:

class Solution {
public:

//从vector头部开始,弹出
int popSameChar(list<char> &vStoreSz, char szOut)
{
char szTempOut = vStoreSz.front();
vStoreSz.pop_front();
while (szTempOut != szOut)
{
szTempOut = vStoreSz.front();
vStoreSz.pop_front();
}

return 0;
}

//最长不重复子串,子串可能位于字符串的中间位置
int lengthOfLongestSubstring(string s) {
list<char> isAppear;
int num;
int maxlen = 0;
int nowLen = 0;
char szTemp;
for (num = 0; num< s.length(); num++)
{
szTemp = s[num];
list<char>::iterator iteFindSz = find(isAppear.begin(), isAppear.end(),szTemp);

if (iteFindSz != isAppear.end())
{
nowLen = isAppear.size();
if (nowLen > maxlen)
{
maxlen = nowLen;

}
popSameChar(isAppear,szTemp);
nowLen = 0;

}
isAppear.push_back(szTemp);
}

nowLen = isAppear.size();
if (nowLen > maxlen)
{
maxlen = nowLen;

}

return maxlen;
}

};


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c++ substring list