Leetcode 159. Longest Substring with At Most Two Distinct Characters (Hard) (cpp)

来源:互联网 发布:linux wget https 404 编辑:程序博客网 时间:2024/04/30 19:15

Leetcode 159. Longest Substring with At Most Two Distinct Characters (Hard) (cpp)

Tag: Hash Table, Two Pointers, String

Difficulty: Hard


/*159. Longest Substring with At Most Two Distinct Characters (Hard)Given a string, find the length of the longest substring T that contains at most 2 distinct characters.For example, Given s = “eceba”,T is "ece" which its length is 3.*/class Solution {public:int lengthOfLongestSubstringTwoDistinct(string s) {if (s.size() < 3) {return s.size();}vector<int> t(256, 0);int sl = 0, f = 0, res = 0, cnt = 0;while (f < s.size()) {if (++t[s[f++]] == 1) {cnt++;}while (cnt > 2) {--t[s[sl++]];if (t[s[sl - 1]] == 0) {cnt--;}}res = max(f - sl, res);}return res;}};


0 0
原创粉丝点击