G面经Prepare: Longest All One Substring

Posted neverlandly

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了G面经Prepare: Longest All One Substring相关的知识,希望对你有一定的参考价值。

give a string, all 1 or 0, we can flip a 0 to 1, find the longest 1 substring after the flipping

 

这是一个简单版本of LC 424 Longest Repeating Character Replacement

又是Window, 又是Two Pointers

Window还是采用每次都try to update left使得window valid, 每次都检查最大window

 1 package GooglePhone;
 2 
 3 public class LongestOneSubstr {
 4     
 5     public static int find2(String str) {
 6         if (str==null || str.length()==0) return 0;
 7         int l = 0, r = 0;
 8         int maxLen = 0;
 9         int countZero = 0;
10         for (r=0; r<str.length(); r++) {
11             if (str.charAt(r) == ‘0‘) countZero++;
12             while (countZero > 1 && l < str.length()) {
13                 if (str.charAt(l) == ‘0‘) countZero--;
14                 l++;
15             }
16             maxLen = Math.max(r-l+1, maxLen);
17         }
18         return maxLen;
19     }
20 
21     /**
22      * @param args
23      */
24     public static void main(String[] args) {
25         // TODO Auto-generated method stub
26         System.out.println(find2("10111000010110111101101010101"));
27     }
28 
29 }

 

以上是关于G面经Prepare: Longest All One Substring的主要内容,如果未能解决你的问题,请参考以下文章

Groupon面经Prepare: Sort given a range && Summary: Bucket Sort

Groupon面经Prepare: Max Cycle Length

2Sigma OA prepare: Longest Chain

FB面经 Prepare: Make Parentheses valid

M面经Prepare: Find integer Average of 2 integers.

FB面经Prepare: Merge K sorted Array