📌  相关文章
📜  具有奇数计数的字典最小数字字符串

📅  最后修改于: 2022-05-13 01:56:06.478000             🧑  作者: Mango

具有奇数计数的字典最小数字字符串

给定一个正整数N ,任务是生成一个大小为N的字典最小数字字符串,每个数字都有奇数。

例子:

方法:可以基于以下观察解决给定的问题:如果N的值为even ,则结果字符串包含1s(N – 1)次后跟单个2是可能的最小字典字符串。否则,结果字符串包含1sN次是可能的最小字典字符串。

下面是上述方法的实现:

C++14
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to construct lexicographically
// smallest numeric string having an odd
// count of each characters
string genString(int N)
{
    // Stores the resultant string
    string ans = "";
 
    // If N is even
    if (N % 2 == 0) {
        ans = string(N - 1, '1') + '2';
    }
 
    // Otherwise
    else {
        ans = string(N, '1');
    }
 
    return ans;
}
 
// Driver code
int main()
{
    int N = 5;
    cout << genString(N);
 
    return 0;
}


Python3
# python program for the above approach
# Function to construct lexicographically
# smallest numeric string having an odd
# count of each characters
def genString(N):
   
    # Stores the resultant string
    ans = ""
 
    # If N is even
    if (N % 2 == 0) :
        ans = "".join("1" for i in range(N-1))
        ans = ans + "2"
     
    # Otherwise
    else :
        ans = "".join("1" for i in range(N))
     
    return ans
   
# Driver code
if __name__ == "__main__":
    N = 5
    print(genString(N))
 
 
# This code is contributed by anudeep23042002


C#
// C# program for the above approach
using System;
class GFG {
 
    // Function to construct lexicographically
    // smallest numeric string having an odd
    // count of each characters
    static string genString(int N)
    {
       
        // Stores the resultant string
        string ans = "";
 
        // If N is even
        if (N % 2 == 0) {
            for (int i = 0; i < N - 1; i++)
                ans += '1';
            ans += '2';
        }
 
        // Otherwise
        else {
            for (int i = 0; i < N; i++)
                ans += '1';
        }
 
        return ans;
    }
 
    // Driver code
    public static void Main()
    {
        int N = 5;
        Console.WriteLine(genString(N));
    }
}
 
// This code is contributed by ukasp.


Javascript


输出:
11111

时间复杂度: O(N)
辅助空间: O(N)