问题描述:求一个字符串中的最大不重复子串
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.
原题地址:https://leetcode.com/problems/longest-substring-without-repeating-characters/
关于字符串的比较经典的问题,网上可以搜到很多解法,博主在论坛里找到一个最简洁的方法,且时间复杂度仅为o(n)。该算法比较另类,主要是通过一个256维的一维数组来实现的。核心思想是把字符串中的字符映射到上述一维数组中,然后通过移动lastrepeatpos来处理有重复字符的情况。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int m[256];
fill(m, m+256, -1);
int maxLen = 0, lastRepeatPos = -1;
for(int i=0; i<s.size(); i++) {
//重复的位置必须要小于当前字符的位置才移动lastrepeatpos
if (m[s[i]]!=-1 && lastRepeatPos < m[s[i]] )
lastRepeatPos = m[s[i]];
//更新计算最大不重复字符串的长度
if ( i - lastRepeatPos > maxLen )
maxLen = i - lastRepeatPos;
m[s[i]] = i;
}
return maxLen;
}
};