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.
To solve this problem, I used two pointers and hashmap. I add an example for illustration.
#include <string>
#include <iostream>
using namespace std;
// "abcabcbb" -> "abc"
// Two Pointers Method
int lengthOfLongestSubstring(string s) {
if(s.size() <= 1) return s.size();
bool map[256] = {false};
int i = 0;
int j = 0;
int maxLen = 0;
while(i < s.size()) {
if(!map[s[i]]) {
map[s[i]] = true;
i++;
} else {
maxLen = max(maxLen, i - j);
while(s[i] != s[j]) {
map[s[j]] = false;
j++;
}
i++;
j++;
}
}
maxLen = max(maxLen, i - j);
return maxLen;
}
int main(void) {
string test = "aab";
int len = lengthOfLongestSubstring(test);
cout << len << endl;
}
本文介绍了一种使用双指针和哈希映射解决最长无重复子字符串问题的方法,并提供了一个示例代码实现。该算法能高效地找出给定字符串中最长的不包含重复字符的子串。
710

被折叠的 条评论
为什么被折叠?



