• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Longest Substring with At Most Two Distinct Characters

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.

方法一:用HashMap, map里面存元素及其出现次数。维护一个最大长度。用两个指针,右指针一直走到出现3个dinstinct character为止。然后调整左指针删元素,直接从左往右逐个字符的删除,一直删到某个字符不会再出现。判断字符被删光就看次数是否减为了0.

 

采用方法:

 1 public class Solution {
 2     public int lengthOfLongestSubstringTwoDistinct(String s) {
 3         if (s==null || s.length()==0) return 0;
 4         HashMap<Character, Integer> map = new HashMap<Character, Integer>();
 5         int longest = 0;
 6         int l = 0;
 7         int r = 0;
 8         while (r < s.length()) {
 9             // move right edge
10             char c = s.charAt(r);
11             map.put(c, map.getOrDefault(c, 0) + 1);
12             
13             // move left edge when necessary to make window valid again
14             while (map.size() >= 3 && l <= r) {
15                 char d = s.charAt(l);
16                 if (map.get(d) > 1) map.put(d, map.get(d)-1);
17                 else map.remove(d);
18                 l++;
19             }
20             
21             // calculate the longest window
22             longest = Math.max(longest, r - l + 1);
23             r ++;
24         }
25         return longest;
26     }
27 }

这里每个元素都会进入窗口一次,最多出窗口一次,所以平摊在每个元素上的时间复杂度是O(1),总时间复杂度为O(N)

 

Method 2: window never shrink,  can possibly be faster

posted @ 2015-01-22 13:17  neverlandly  阅读(398)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3