本文共 1458 字,大约阅读时间需要 4 分钟。
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, 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.
class Solution {public: int lengthOfLongestSubstring(string s) { if("" == s) return 0; //空串 if(1 == s.length()) return 1; //只有一个字符 if(2==s.length() && s.at(0)!=s.at(1)) return 2; int left(0), right(1), len(s.length()), max_len(1); unordered_set setv; setv.insert(s.at(left)); while(right < len) { if(setv.count(s.at(right)) != 0) { setv.erase(s.at(left)); ++left; } //在集合中删除元素,直到没有与当前字符重复的时候 else { setv.insert(s.at(right)); ++right; max_len = max(max_len, (int)setv.size()); //记录最大的长度 } } return max_len; }};
转载地址:http://eykhj.baihongyu.com/