typical sliding window problem with tiny changes
This is a sliding window type of question, and I am sure Lee\'s post explained enough about the logic behind. I am posting this to share my code template, which
This is a sliding window type of question, and I am sure Lee\'s post explained enough about the logic behind. I am posting this to share my code template, which can be applied to multiple sliding window questions. A few points below,\n* two pointers, **start** and **end**\n* a while loop to control the **end** pointer so that it can iterate the whole string\n* **count** variable to remember how many unique keys\n* start pointer moves only if it doesn\'t affect **count** variable.\n\nFor this question, the only differece is how **res** is calculated. When you find `count == 3`, all the substrings start with s.charAt(start) is a substring that meets the requirement. The end of the substring is from **end pointer** until the end of the input string.\n\nTime, O(n)\nSpace, O(1) - the space taken by the `letters` array can almost be ignored\n\n```\nclass Solution {\n    public int numberOfSubstrings(String s) {\n        int len = s.length();\n        int[] letter = new int[3];\n        int count = 0;\n        int res = 0;\n        int start = 0;\n        int end = 0;\n        while (end < s.length()) {\n            char c1 = s.charAt(end);\n            if (letter[c1 - \'a\']++ == 0) {\n                count++;\n            }\n            while (count == 3) {\n                res += len - end;\n                char c2 = s.charAt(start);\n                if (letter[c2 - \'a\']-- == 1) {\n                    count--;\n                }\n                start++;\n            }\n            end++;\n        }\n        return res;\n    }\n}\n```\n\nAt last, here is [a collection of sliding window problems](https://www.cnblogs.com/cnoodle/tag/sliding%20window/) that I found so far. Hope it helps.
['Two Pointers', 'Sliding Window', 'Java']