欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Longest Substring with At Most Two Distinct

发布时间:2024/4/17 编程问答 53 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Longest Substring with At Most Two Distinct 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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.

用p1 & p2 两个pointer分别纪录当前window里两个character最后一次发生时的index,用start纪录window开始时的index。
从index 0开始遍历String:

如果当前的character在window内,update相应的pointer。

如果不在,比较两个character的pointer,去掉出现较早的那个character, 更新start=min(p1,p2)+1

时间复杂度是O(n), 空间复杂度是O(1):

 

1 public class Solution { 2 public int lengthOfLongestSubstringTwoDistinct(String s) { 3 int result = 0; 4 int first = -1, second = -1; 5 int win_start = 0; 6 for(int i = 0; i < s.length(); i ++){ 7 if(first < 0 || s.charAt(first) == s.charAt(i)) first = i; 8 else if(second < 0 || s.charAt(second) == s.charAt(i)) second = i; 9 else{ 10 int min = first < second ? first : second; 11 win_start = min + 1; 12 if(first == min) first = i; 13 else second = i; 14 } 15 result = Math.max(result, i - win_start + 1); 16 } 17 return result; 18 } 19 }

 

转载于:https://www.cnblogs.com/reynold-lei/p/4247706.html

总结

以上是生活随笔为你收集整理的Longest Substring with At Most Two Distinct的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。