0 ms || Beats 100% users || Java
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires generating a string of length a + b such that there are no three c
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires generating a string of length a + b such that there are no three consecutive \'a\'s or \'b\'s. This can be achieved by alternating between \'a\' and \'b\' characters while ensuring that at no point there are more than two consecutive characters of the same type.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nsolve(a,b,s): This method appends \'b\' and \'a\' alternatively to the result string until both a and b are exhausted.\nDepending on whether a or b is greater, it alternates between appending \'a\' and \'b\' to avoid three consecutive characters of the same type. We make use of variable ac, bc to keep count of a and b appended to the string. After ensuring a and b are balanced, it appends any remaining characters to result string.\n\n# Complexity\n- Time complexity: O(a+b) - This is because each iteration or append operation runs in constant time, and we iterate at most a + b times.\n\n- Space complexity: O(a+b) - This is primarily due used to construct the result string, which grows linearly with the sum of a and b.\n\n# Code\n```\nclass Solution {\n    public String solve(int a,int b,String s){\n        StringBuilder sb=new StringBuilder(s);\n        while(a>0&&b>0){\n                sb.append(\'b\');\n                sb.append(\'a\');\n                a--;\n                b--;\n            }\n        return sb.toString();\n    }\n    public String strWithout3a3b(int a, int b) {\n        StringBuilder sb=new StringBuilder();\n        int ac=0,bc=0;\n\n        if(a==b)\n        return solve(a,b,sb.toString());\n        if(a>b){\n            while(a>0&&b>0){\n                sb.append(\'a\');\n                ac++;\n                a--;\n                if(ac%2==0){\n                    sb.append(\'b\');\n                    bc++;\n                    b--;\n                }\n                if(a==b){\n                   return solve(a,b,sb.toString());\n                }\n            }\n        }\n        else {\n            while(a>0&&b>0){\n                sb.append(\'b\');\n                bc++;\n                b--;\n                if(bc%2==0){\n                    sb.append(\'a\');\n                    ac++;\n                    a--;\n                }\n                if(a==b){\n                   return solve(a,b,sb.toString());\n                }\n            }\n        }\n\n        while(a>0){sb.append(\'a\'); a--;}\n        while(b>0){sb.append(\'b\'); b--;}\n        return sb.toString();\n    }\n}\n```
['Java']