【LeetCode】3.无重复字符的最长子串 结题报告 (C++)
2018-04-11 20:31
686 查看
题目地址:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/description/给定一个字符串,找出不含有重复字符的 最长子串 的长度。示例:给定
public:
int lengthOfLongestSubstring(string s) {
int max = 0;
int tmp = 0;
int l, r, i;
int N = s.size();
for(l = 0, r = 0; r <= N; r ++){
for(i = l; i <= r; i ++){
if(s[i] == s[r]){
if(tmp > max) max = tmp;
break;
}
}
if(i == r) tmp ++;
else{
l = i + 1;
tmp = r - i;
}
}
return max;
}
};网上查找比较好的方法:
时间复杂度O(n), 空间复杂度是O(n), 额外开辟内存空间O(1)分析:遍历该字符串,每遍历一个字母时,利用map去找该字母最近一次出现是什么时候,中间这一段便是无重复字符的字符串。class Solution {
public:
/**
* @param s: a string
* @return: an integer
*/
int lengthOfLongestSubstring(string s) {
// write your code here
int ret = 0;
map<char, int> m;
int start = 1;
for (int i = 1; i <= s.length(); i++)
{
char c = s[i - 1];
if (m[c] >= start)
{
start = m[c] + 1;
m[c] = i;
}
else
{
m[c] = i;
ret = max(ret, i - start + 1);
}
}
return ret;
}
};
"abcabcbb",没有重复字符的最长子串是
"abc",那么长度就是3。给定
"bbbbb",最长的子串就是
"b",长度是1。给定
"pwwkew",最长子串是
"wke",长度是3。请注意答案必须是一个子串,
"pwke"是 子序列 而不是子串。解题方法:class Solution {
public:
int lengthOfLongestSubstring(string s) {
int max = 0;
int tmp = 0;
int l, r, i;
int N = s.size();
for(l = 0, r = 0; r <= N; r ++){
for(i = l; i <= r; i ++){
if(s[i] == s[r]){
if(tmp > max) max = tmp;
break;
}
}
if(i == r) tmp ++;
else{
l = i + 1;
tmp = r - i;
}
}
return max;
}
};网上查找比较好的方法:
时间复杂度O(n), 空间复杂度是O(n), 额外开辟内存空间O(1)分析:遍历该字符串,每遍历一个字母时,利用map去找该字母最近一次出现是什么时候,中间这一段便是无重复字符的字符串。class Solution {
public:
/**
* @param s: a string
* @return: an integer
*/
int lengthOfLongestSubstring(string s) {
// write your code here
int ret = 0;
map<char, int> m;
int start = 1;
for (int i = 1; i <= s.length(); i++)
{
char c = s[i - 1];
if (m[c] >= start)
{
start = m[c] + 1;
m[c] = i;
}
else
{
m[c] = i;
ret = max(ret, i - start + 1);
}
}
return ret;
}
};
相关文章推荐
- LeetCode 3. 无重复字符的最长子串
- Leetcode 3. 无重复字符的最长子串
- [LeetCode] Longest Substring Without Repeating Characters 无重复字符的最长子串
- LeetCode-3:Longest Substring Without Repeating Characters (最长无重复字符的子串) --medium
- [leetcode]Longest Substring Without Repeating Characters【最长不重复字符子串】
- [leetcode]无重复字符的最长子串
- LeetCode题库解答与分析——#3.无重复字符的最长子串LongestSubstringWithoutRepeatingCharacters
- 【LeetCode题目记录-3】字符串中最长的没有重复字符的子串
- C++找出字符串中最长的不含重复字符的子串
- 3.无重复字符的最长子串(Longest Substring Without Repeating Characters)
- 3. 无重复字符的最长子串
- Leetcode 刷题(python)之 无重复字符的最长子串
- LeetCode - 无重复字符的最长子串
- leetcode-最长无重复字符的子串
- [LeetCode]3. Longest Substring Without Repeating Characters寻找最长无重复字符的子串
- 3. 无重复字符的最长子串(O(N))
- LeetCode: 3_Longest Substring Without Repeating Characters | 求没有重复字符的最长子串的长度 | Medium
- 【leetcode】第3题:求最长不重复(字符不重复)的子串的长度
- [leetcode]获取字符串中字符不重复的最长子串的长度
- 【中级算法】3. 无重复字符的最长子串