码迷,mamicode.com
首页 > 其他好文 > 详细

LC 984. String Without AAA or BBB

时间:2019-02-05 13:05:51      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:2-2   exist   correct   ESS   int   str   style   runtime   help   

 

Given two integers A and B, return any string S such that:

  • S has length A + B and contains exactly A ‘a‘ letters, and exactly B ‘b‘ letters;
  • The substring ‘aaa‘ does not occur in S;
  • The substring ‘bbb‘ does not occur in S.

 

Example 1:

Input: A = 1, B = 2
Output: "abb"
Explanation: "abb", "bab" and "bba" are all correct answers.

Example 2:

Input: A = 4, B = 1
Output: "aabaa"

 

Note:

  1. 0 <= A <= 100
  2. 0 <= B <= 100
  3. It is guaranteed such an S exists for the given A and B.
Runtime: 0 ms, faster than 100.00% of C++ online submissions for String Without AAA or BBB.
Memory Usage: 753.7 KB, less than 100.00% of C++ online submissions for String Without AAA or BBB.

 

class Solution {
public:
  string strWithout3a3b(int A, int B) {
    if(A <= B) {
      return helper("b","a", B, A);
    }
    return helper("a","b", A, B);
  }

  string helper(string more, string less, int m, int l){
    string ret = "";
    if( m - l > l) {
      //assert(m - l <= 3);
      for(int i=0; i<l; i++){
        ret += more + more + less;
      }
      for(int i=0; i< m - l - l; i++) {
        ret += more;
      }
    }
    else {
      for(int i=0; i<m-l; i++) {
        ret += more + more + less;
      }
      for(int i=0; i<2*l-m; i++){
        ret += more + less;
      }
    }
    return ret;
  }

};

 

LC 984. String Without AAA or BBB

标签:2-2   exist   correct   ESS   int   str   style   runtime   help   

原文地址:https://www.cnblogs.com/ethanhong/p/10352642.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!