题目来源:https://leetcode.com/problems/longest-substring-without-repeating-characters/
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.
第一感觉应该是动态规划问题。
思路:讲字符串从前往后遍历,遍历时,计算以s[i]结尾的最长不重复子串的长度,然后和以前保存的长度进行比较即可。时间复杂度O(len*N)。
代码如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.size() == 0)return 0;
int len = 1;
int templen = 1;
for (int i = 1; i < s.size(); i++)
{
int j = i-1;
while (j>=i-templen && s[j] != s[i])
{
j--;
}
if (j >= i - templen)
{
templen = i-j;
}
else
templen++;
len = len > templen ? len : templen;
}
return len;
}
};