码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Longest Substring with At Most Two Distinct Characters

时间:2015-07-14 13:20:40      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:

Problem Description

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.

This link has a nice solution to this problem using the sliding window technique. The code is rewritten as follows.

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstringTwoDistinct(string s) {
 4         int l = 0, r = -1, len = 0, n = s.length();
 5         for (int k = 1; k < n; k++) {
 6             if (s[k] == s[k - 1]) continue;
 7             if (r >= 0 && s[k] != s[r]) {
 8                 len = max(len, k - l);
 9                 l = r + 1;
10             }
11             r = k - 1;
12         }
13         return max(n - l, len);
14     }
15 };

 

[LeetCode] Longest Substring with At Most Two Distinct Characters

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4644357.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!