JAVA Solution | Consecutive Characters | 2ms |
Intuition\n Describe your first thoughts on how to solve this problem. \nThis problem requires finding the maximum length of a consecutive substring that consis
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem requires finding the maximum length of a consecutive substring that consists of the same character.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can iterate over the string and maintain two variables - power and currPower. power is used to store the maximum length of consecutive substring seen so far, and currPower is used to store the length of the current consecutive substring being considered.\n\nFor each character in the string, we compare it to the previous character. If they are the same, we increment currPower. If they are different, we update power to be the maximum of power and currPower, and reset currPower to 1.\n\nFinally, we return the maximum of power and currPower, since we need to consider the last consecutive substring seen as well.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this solution is O(n), where n is the length of the input string. This is because we need to iterate over each character in the string exactly once.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of this solution is O(1), since we only need to store two integer variables regardless of the size of the input string.\n\n# Code\n```\nclass Solution {\n    public int maxPower(String s) {\n        int power = 1, currPower = 1;\n        for(int i = 1 ; i < s.length(); i++)\n        {\n            if(s.charAt(i) == s.charAt(i - 1))\n            {\n                currPower++;\n            }\n            else\n            {\n                power = Math.max(power, currPower);\n                currPower = 1;\n            }\n        }\n\n        return Math.max(power, currPower);\n    }\n}\n```
['String', 'Java']