首页 > 代码库 > G面经Prepare: Longest All One Substring

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