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.

问题解决方法:

1)设当前连续未出现重复字符计数nCount,nCount初始化为1,设当前最长无重复字符子串长度为nRet,nRet初始化为0;

2)将待遍历字符串s的第一个字符赋值给当前最大字符子串maxStr.

3)然后从字符串s的第i(2 <= i,且小于串s的长度)个字符s[i]开始遍历,判断s[i]是否存在最大字符子串中,若存在,需要分情况优化,视s[i]字符在当前最大子串maxStr中的位置:a、在maxStr的最后位置,则令最大字符子串maxStr = s[i++];b、在maxStr的其他位置,令maxStr = maxStr.substr(index+1),这样做的原因是s[i]只与maxStr中一个字符重复,重复字符之后的字符完全和s[i]不重复,故不需要再与这些元素比较是否相同,此时nCount = maxStr.length();若不存在,则maxStr += s[i++],并且nCount++。

4)重复第3步,直到遍历字符位置i == s.length().

从以上的步骤推断算法复杂度是:O(n)* k ,k为最大子串长度,并不是很快,在leetcode上属于中等水平,可怜,有时间再优化吧!有更好思路的童鞋可以告诉我。

算法代码实现如下:

#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.empty())
            return 0;
		unsigned int len = s.length();
		unsigned int nRet = 0;
		unsigned int i = 1;
		string maxStr;
		maxStr = s[0];
		unsigned int nCount = 1;
		while(i < len){
			string::size_type index = maxStr.find(s[i], 0);
			if(index != string::npos){                          //在当前最大子串中找到字符s[i]
                string::size_type s_index = s.find(maxStr, 0);
				if(s_index+index+1 != i && index+1 < maxStr.length()){             //若找到的位置不在最大子串中的末尾
					maxStr = maxStr.substr(index+1);            //则设置当前最大子串为找到位置的下一个字符开始的子串
				}
				else{                                           //找到位置是最大子串的末尾
					maxStr = s[i++];                            //则设置当前最大子串为找到的重复字符,且串从下一个位置开始遍历
				}
				if(nRet < nCount)
					nRet = nCount;
				nCount = maxStr.length();
			}
			else{
				maxStr += s[i];
				++nCount;
				++i;
			}
		}
		return nRet > nCount ? nRet:nCount;
    }
};

int main()
{
	string s("abcabcbb");
	//string s("abcdefg");
	//string s("");
	//string s("aab");
	//string s("eeee");
	//string s("anviaj");

	Solution sol;
	int nRet = sol.lengthOfLongestSubstring(s);
	cout << nRet << endl;
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值