题目描述
出处:https://leetcode.com/problems/longest-substring-without-repeating-characters
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, which the length is 3.
Example 2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: “pwwkew”
Output: 3
Explanation: 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.
分析
这道题主要的考点是对字符串的处理,要注意题干的要求
- 要求连续不同的字符串
- 若出现与前面相同的字符,应该从相同字符的下一个字符开始计算
如:“abac”,当识别第二个‘a’时,应该从‘b’开始继续计算
即:在识别字符是,既要比较是否有重复,也要同时记录其出现的位置,因此可以使用vector,在对应字符的位置记录该字符前一次出现的位置。
最终结果
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> string(256,-1);
int count = 0, start = -1, now = 0;
for (now = 0; now <s.length(); now++) {
if (string[s[now]] > start)
start = string[s[now]];
string[s[now]] = now;
if (count < now-start)
count = now-start;
}
return count;
}
};