leetcode-984. 不含 AAA 或 BBB 的字符串

class Solution {
    public String strWithout3a3b(int A, int B) {
        StringBuilder ans = new StringBuilder();
        int size = A+B;
        int a = 0, b = 0;
        for(int i = 0; i < size; i++){
            if((A >= B && a != 2)  || b == 2){ 
                ans.append("a");
                A--;
                a++;
                b = 0;
            }else if((B >= A && b != 2) || a == 2) {
                ans.append("b");
                b++;
                B--;
                a = 0;
            }
            
        }
        
        return ans.toString();
    }
}
string strWithout3a3b(int A, int B, char a = 'a', char b = 'b', string res = "") {
  if (B > A) swap(A, B), swap(a, b);
  while (A > 0 || B > 0) {
    if (A > 0) res += a, A--;
    if (A > B) res += a, A--;
    if (B > 0) res += b, B--;
  }
  return res;
}

猜你喜欢

转载自blog.csdn.net/qq_39370495/article/details/86665536