Tuesday, December 16, 2014

【leetcode】 Longest Substring with At Most Two Distinct Characters

Question:
Given a string S, find the length of the longest substring T that contains at most two
distinct characters.
For example,
Given S = “eceba”,
T is "ece" which its length is 3.

代码: 这里

我用的是O(n^3)的方法,不知道怎么更好的剪支,其实在调试的时候发现,一旦发现第二个循环出现了超过2个字符的情况就可以直接调到外层循环了,就是不知道怎么写代码。

另一种方法是,维护一个sliding window保证这个窗口中的字符串最多只有两种,维护start和end的指针,记录每个字符出现的次数,当第三个字符出现时,加入到map中,并且把map中记录的start位置上的字符串删掉,如果start位置上的字符串有多个,就循环将计数器减一,直到为零,然后删除start位置的字符串

代码如下:这里

No comments:

Post a Comment