[JAVA] Short O(n) time O(1) space Sliding Window solution w/ explaination
Our target is to convert the original s to either 010101010... or 101010101.... So here we can just check whether index after type-1 transformation is odd or ev
Our target is to convert the original `s` to either *010101010...* or *101010101...*. So here we can just check whether index after type-1 transformation is odd or even. \n* Type-1 transform could be done with `i%n` or `i-n`, when our i ranged from 0 to 2\\*n. Here in the code, it is `s.charAt(i%n)` when `i >= n`.\n* Type-2 transform is to compare the value of index `s[i%n]` with `i` \'s even or odd attribute.\n* 2 results would either be `t` or `n-t` (one is for  *010101010...*, another is for  *101010101...*). We just get Min of them.\n\nThere would be a sliding window, when `i < n`, we just add new number to the window, when `i >= n`, we remove the previous number we added into the window. \n\nAnd note that the original length of string s may be odd, so when we add new number into the sliding window, we are checking `i` itself. When removing previous number, we are checking `i%n`, since the previous number we added is `i%n`.\n\nJAVA code:\n\n```\n    public int minFlips(String s) {\n        int n = s.length(), res = Integer.MAX_VALUE, t = 0;        \n        for (int i = 0; i < 2*n; i++)  {\n            if (s.charAt(i%n) - \'0\' != (i % 2 != 0 ? 0 : 1) ) t++; // add is i\n            if (i >= n && s.charAt(i%n) - \'0\' != (i%n % 2 != 0 ? 0 : 1)) t--; // minus is i%n\n            if (i >= n-1)  res = Math.min(res, Math.min(t, n-t));             \n        }\n        return res;\n    }\n```
['Sliding Window', 'Java']