Type:medium
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"Output: 3Explanation:The answer is"abc", with the length of 3.
Example 2:
Input: "bbbbb"Output: 1Explanation: The answer is"b", with the length of 1.
Example 3:
Input: "pwwkew"Output: 3Explanation: The answer is"wke", with the length of 3. Note that the answer must be asubstring,"pwke"is asubsequenceand not a substring.
本题旨在寻找字符串中最长无重复字符子串。
本题基本解题思路为建立两个指针i、j,指针i指向无重复的子字符串的第一位,指针j指向最后一位。在遍历s的过程中,指针j向前遍历,若遇到重复的字符则指针i指向这个重复的字符,指针j继续向后遍历,直至读取完整个s字符串。j、i间的距离就为最长无重复子字符串。
有一个很巧妙的想法,从ASCII角度考虑,每一个字符(32-126)都可以转为int型。因此建立一个名叫count的vector<int>型,大小可以为126。建立int型start记录首字符的位置,赋为初始值-1,maxlen记录该子字符串长度,赋为初始值0。首先把所有count值都赋值为-1,然后读取string字符串,由于初始化下count[s[i]]均为-1,因此可用来判断是否之前有重复字符串。因此在读取s过程中,首先判断count[s[i]]的值是否为-1,若是-1,说明s中该第i位还未重复,并将count[s[i]]设为i值,即它在s中的位置;若count[s[i]]不为-1,说明在这之前已经读取过s[i],则赋start = count[s[i]],即为上一次重复的字符位置。此时,i - start即为该子字符串的长度。比较maxlen与该值的大小,取最大值为新的maxlen。
当i读取到最后一位,返回maxlen,即为所求结果。
附代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.length();
int i;
vector<int> count(128, -1) ;
int start = -1;
int maxlen = 0;
for(i=0; i<n; i++){
if(count[s[i]] > start) start = count[s[i]];
count[s[i]] = i;
maxlen = max(i-start, maxlen);
}
return maxlen;
}
};