您的位置:首页 > 其它

LeetCode3:Longest Substring Without Repeating Characters

2015-10-16 22:53 281 查看
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.


一、题目描述

基本意思是从字符串中找出不含重复字符的最大长度子串,输出最大子串的长度,例如字符串“abcdab”的最大子串为“abcd”,长度即为4。


二、解题思路

分析:假设子串里含有重复字符,则父串一定含有重复字符,单个子问题就可以决定父问题,因此可以利用贪心法求解。
从左往右扫描,当遇到重复字母时,将上一个重复字母的index+1,作为新的搜索起始位置,直到字符串的最后一个字母。
算法时间复杂度O(n),空间复杂度O(1)。因为ASCLL码字符个数128个,这里用unorder_map打表记录每个字符在字符串中最后出现的位置,unordered_map的空间消耗最大为128,所以时间复杂度是常数级的。unordered_map的查找插入操作的时间复杂度都是O(1),所以整个算法的时间度为O(n)。



#include<iostream>
#include<algorithm>
#include<unordered_map>
using namespace std;

class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> map;//map记录遍历过程中每个字符最后出现的位置
int mLength = 0, i = 0, j = 0; //mLength记录不重复字符子串的最大长度,i记录当前不重复子串的起点,j记录当前不重复子串的终点

while (j<s.size()){ //遍历字符串
if (map.find(s[j]) != map.end() && map[s[j]] >= i) //如果当前维护的不重复子串中出现了s[j]
//在找是否出现重复字符的时候,一定要在当前考察的子串的范围内查找,所以条件 && um[s[i]]  >= j不能漏
i= map[s[j]] + 1;   //更新i
else  //如果当前维护的不重复子串中没有出现s[j]
mLength = max(mLength, j - i+ 1); //更新结果,取较大者

map[s[j]] = j; //更新mLength
j++;
}
return mLength;
}
};

int main()
{
string s1 = "abcdabc";
Solution Sol;
int n = 0;
n = Sol.lengthOfLongestSubstring(s1);
cout << "The length of longest substring is : " << n << endl;
system("pause");
return 0;
}




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