zoukankan      html  css  js  c++  java
  • [leetcode] 984. String Without AAA or BBB(贪心算法!!!)

    原题:

    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.
     思路:
    贪心算法!!!!
     

    c++代码实现:

    class Solution {
    public:
        string strWithout3a3b(int A, int B) {
            string ans="";
            char a='a',b='b';
            if(A<B){
                swap(A,B);
                swap(a,b);
            }
            while(A||B){
                if(A>0) {ans+= a; A--;}
                if(A>B) {ans+= a; A--;}
                if(B>0) {ans+= b; B--;}
            }
            return ans;
        }
    };
  • 相关阅读:
    记一次mqtt压测过程
    记项目过程中代码分支管理
    测试流程
    Docker与K8s的区别
    Mysql之pymysql
    Mysql常用简介
    JQuery
    CSS
    红外线接受程序 理解
    数码管流水灯升级程序理解
  • 原文地址:https://www.cnblogs.com/guweixin/p/10438845.html
Copyright © 2011-2022 走看看