LeetCode: Longest Substring Without Repeating Characters (3)
2018-02-09 16:54
218 查看
Given a string, find the length of the longest substring without repeating characters.Examples:Given
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> hash(256,-1);
int sMax = 0;
int latestStart = 0;
int start =0;
for(int i= 0;i<s.length();i++)
{
//repeat char
if(hash[s[i]]!= -1)
{
sMax = max(sMax,i-start);
latestStart = start;
start = hash[s[i]]+1;
for(int j = latestStart;j<start;j++)
hash[s[j]] = -1;
}
hash[s[i]] = i;
}
return max(sMax,s.length()-start);
}
};
"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.思路: 求最长不重复子字符串类问题, 可以将字符串按照顺序存放在连续的数组中即可。 在存入的时候判断是否重复,做香烟处理。遍历一次即可得到最长子串。时间复杂度:O(n)扩展:求最长重复子字符串#define max(x,y) (x>y)?(x):(y)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> hash(256,-1);
int sMax = 0;
int latestStart = 0;
int start =0;
for(int i= 0;i<s.length();i++)
{
//repeat char
if(hash[s[i]]!= -1)
{
sMax = max(sMax,i-start);
latestStart = start;
start = hash[s[i]]+1;
for(int j = latestStart;j<start;j++)
hash[s[j]] = -1;
}
hash[s[i]] = i;
}
return max(sMax,s.length()-start);
}
};
相关文章推荐
- 【编程】leetcode_longest substring without repeating characters
- Leetcode Probelm.3 Longest Substring Without Repeating Characters
- leetcode_Longest Substring Without Repeating Characters
- LeetCode - 4 - Longest Substring Without Repeating Characters
- [LeetCode]3 Longest Substring Without Repeating Characters
- LeetCode Algorithm Longest Substring Without Repeating Characters
- Leetcode-- Longest Substring Without Repeating Characters
- leetcode-3-Longest Substring Without Repeating Characters
- LeetCode #Longest Substring Without Repeating Characters#
- leetcode3-Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- leetcode:Longest Substring Without Repeating Characters
- [Leetcode]Longest Substring Without Repeating Characters
- LeetCode | Longest Substring Without Repeating Characters
- LeetCode 3 Longest Substring Without Repeating Characters
- leetcode 3 -- Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters