📌  相关文章
📜  从给定序列中形成最小数

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

从给定序列中形成最小数

给定一个只包含 I 和 D 的模式。 I表示增加, D表示减少。设备一个算法来打印遵循该模式的最小数字。 1-9 的数字和数字不能重复。

例子:

Input: D        Output: 21
   Input: I        Output: 12
   Input: DD       Output: 321
   Input: II       Output: 123
   Input: DIDI     Output: 21435
   Input: IIDDD    Output: 126543
   Input: DDIDDIID Output: 321654798

来源:亚马逊面试题

我们强烈建议您单击此处并进行练习,然后再继续使用解决方案。

以下是一些重要的观察

由于数字不能重复,因此输出最多可以有 9 个数字。

此外,输出中的位数比输入中的字符数多一。请注意,输入的第一个字符对应于输出中的两位数。

想法是迭代输入数组并跟踪迄今为止打印的最后一个打印数字和最大数字。下面是上述想法的实现。

C++
// C++ program to print minimum number that can be formed
// from a given sequence of Is and Ds
#include 
using namespace std;
 
// Prints the minimum number that can be formed from
// input sequence of I's and D's
void PrintMinNumberForPattern(string arr)
{
    // Initialize current_max (to make sure that
    // we don't use repeated character
    int curr_max = 0;
 
    // Initialize last_entry (Keeps track for
    // last printed digit)
    int last_entry = 0;
 
    int j;
 
    // Iterate over input array
    for (int i=0; i


Java
// Java program to print minimum number that can be formed
// from a given sequence of Is and Ds
class GFG
{
     
    // Prints the minimum number that can be formed from
    // input sequence of I's and D's
    static void PrintMinNumberForPattern(String arr)
    {
        // Initialize current_max (to make sure that
        // we don't use repeated character
        int curr_max = 0;
 
        // Initialize last_entry (Keeps track for
        // last printed digit)
        int last_entry = 0;
 
        int j;
 
        // Iterate over input array
        for (int i = 0; i < arr.length(); i++)
        {
            // Initialize 'noOfNextD' to get count of
            // next D's available
            int noOfNextD = 0;
 
            switch (arr.charAt(i))
            {
                case 'I':
                    // If letter is 'I'
 
                    // Calculate number of next consecutive D's
                    // available
                    j = i + 1;
                    while (j < arr.length() && arr.charAt(j) == 'D')
                    {
                        noOfNextD++;
                        j++;
                    }
 
                    if (i == 0)
                    {
                        curr_max = noOfNextD + 2;
 
                        // If 'I' is first letter, print incremented
                        // sequence from 1
                        System.out.print(" " + ++last_entry);
                        System.out.print(" " + curr_max);
 
                        // Set max digit reached
                        last_entry = curr_max;
                    }
                    else
                    {
                        // If not first letter
 
                        // Get next digit to print
                        curr_max = curr_max + noOfNextD + 1;
 
                        // Print digit for I
                        last_entry = curr_max;
                        System.out.print(" " + last_entry);
                    }
 
                    // For all next consecutive 'D' print
                    // decremented sequence
                    for (int k = 0; k < noOfNextD; k++)
                    {
                        System.out.print(" " + --last_entry);
                        i++;
                    }
                    break;
 
                // If letter is 'D'
                case 'D':
                    if (i == 0)
                    {
                        // If 'D' is first letter in sequence
                        // Find number of Next D's available
                        j = i + 1;
                        while (j < arr.length()&&arr.charAt(j) == 'D')
                        {
                            noOfNextD++;
                            j++;
                        }
 
                        // Calculate first digit to print based on
                        // number of consecutive D's
                        curr_max = noOfNextD + 2;
 
                        // Print twice for the first time
                        System.out.print(" " + curr_max + " " + (curr_max - 1));
 
                        // Store last entry
                        last_entry = curr_max - 1;
                    }
                    else
                    {
                        // If current 'D' is not first letter
 
                        // Decrement last_entry
                        System.out.print(" " + (last_entry - 1));
                        last_entry--;
                    }
                    break;
            }
        }
        System.out.println();
    }
 
    // Driver code
    public static void main(String[] args)
    {
        PrintMinNumberForPattern("IDID");
        PrintMinNumberForPattern("I");
        PrintMinNumberForPattern("DD");
        PrintMinNumberForPattern("II");
        PrintMinNumberForPattern("DIDI");
        PrintMinNumberForPattern("IIDDD");
        PrintMinNumberForPattern("DDIDDIID");
    }
}
 
// This code is contributed by Princi Singh


Python3
# Python3 program to print minimum number that
# can be formed from a given sequence of Is and Ds
 
# Prints the minimum number that can be formed from
# input sequence of I's and D's
def PrintMinNumberForPattern(arr):
 
    # Initialize current_max (to make sure that
    # we don't use repeated character
    curr_max = 0
 
    # Initialize last_entry (Keeps track for
    # last printed digit)
    last_entry = 0
    i = 0
 
    # Iterate over input array
    while i < len(arr):
 
        # Initialize 'noOfNextD' to get count of
        # next D's available
        noOfNextD = 0
        if arr[i] == "I":
 
            # If letter is 'I'
 
            # Calculate number of next consecutive D's
            # available
            j = i + 1
            while j < len(arr) and arr[j] == "D":
                noOfNextD += 1
                j += 1
            if i == 0:
                curr_max = noOfNextD + 2
                last_entry += 1
 
                # If 'I' is first letter, print incremented
                # sequence from 1
                print("", last_entry, end = "")
                print("", curr_max, end = "")
 
                # Set max digit reached
                last_entry = curr_max
            else:
 
                # If not first letter
 
                # Get next digit to print
                curr_max += noOfNextD + 1
 
                # Print digit for I
                last_entry = curr_max
                print("", last_entry, end = "")
 
            # For all next consecutive 'D' print
            # decremented sequence
            for k in range(noOfNextD):
                last_entry -= 1
                print("", last_entry, end = "")
                i += 1
 
        # If letter is 'D'
        elif arr[i] == "D":
            if i == 0:
 
                # If 'D' is first letter in sequence
                # Find number of Next D's available
                j = i + 1
                while j < len(arr) and arr[j] == "D":
                    noOfNextD += 1
                    j += 1
 
                # Calculate first digit to print based on
                # number of consecutive D's
                curr_max = noOfNextD + 2
 
                # Print twice for the first time
                print("", curr_max, curr_max - 1, end = "")
 
                # Store last entry
                last_entry = curr_max - 1
            else:
 
                # If current 'D' is not first letter
 
                # Decrement last_entry
                print("", last_entry - 1, end = "")
                last_entry -= 1
        i += 1
    print()
 
# Driver code
if __name__ == "__main__":
    PrintMinNumberForPattern("IDID")
    PrintMinNumberForPattern("I")
    PrintMinNumberForPattern("DD")
    PrintMinNumberForPattern("II")
    PrintMinNumberForPattern("DIDI")
    PrintMinNumberForPattern("IIDDD")
    PrintMinNumberForPattern("DDIDDIID")
 
# This code is contributed by
# sanjeev2552


C#
// C# program to print minimum number that can be formed
// from a given sequence of Is and Ds
using System;
     
class GFG
{
     
    // Prints the minimum number that can be formed from
    // input sequence of I's and D's
    static void PrintMinNumberForPattern(String arr)
    {
        // Initialize current_max (to make sure that
        // we don't use repeated character
        int curr_max = 0;
 
        // Initialize last_entry (Keeps track for
        // last printed digit)
        int last_entry = 0;
 
        int j;
 
        // Iterate over input array
        for (int i = 0; i < arr.Length; i++)
        {
            // Initialize 'noOfNextD' to get count of
            // next D's available
            int noOfNextD = 0;
 
            switch (arr[i])
            {
                case 'I':
                    // If letter is 'I'
 
                    // Calculate number of next consecutive D's
                    // available
                    j = i + 1;
                    while (j < arr.Length && arr[j] == 'D')
                    {
                        noOfNextD++;
                        j++;
                    }
 
                    if (i == 0)
                    {
                        curr_max = noOfNextD + 2;
 
                        // If 'I' is first letter, print incremented
                        // sequence from 1
                        Console.Write(" " + ++last_entry);
                        Console.Write(" " + curr_max);
 
                        // Set max digit reached
                        last_entry = curr_max;
                    }
                    else
                    {
                        // If not first letter
 
                        // Get next digit to print
                        curr_max = curr_max + noOfNextD + 1;
 
                        // Print digit for I
                        last_entry = curr_max;
                        Console.Write(" " + last_entry);
                    }
 
                    // For all next consecutive 'D' print
                    // decremented sequence
                    for (int k = 0; k < noOfNextD; k++)
                    {
                        Console.Write(" " + --last_entry);
                        i++;
                    }
                    break;
 
                // If letter is 'D'
                case 'D':
                    if (i == 0)
                    {
                        // If 'D' is first letter in sequence
                        // Find number of Next D's available
                        j = i + 1;
                        while (j < arr.Length&&arr[j] == 'D')
                        {
                            noOfNextD++;
                            j++;
                        }
 
                        // Calculate first digit to print based on
                        // number of consecutive D's
                        curr_max = noOfNextD + 2;
 
                        // Print twice for the first time
                        Console.Write(" " + curr_max + " " + (curr_max - 1));
 
                        // Store last entry
                        last_entry = curr_max - 1;
                    }
                    else
                    {
                        // If current 'D' is not first letter
 
                        // Decrement last_entry
                        Console.Write(" " + (last_entry - 1));
                        last_entry--;
                    }
                    break;
            }
        }
        Console.WriteLine();
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        PrintMinNumberForPattern("IDID");
        PrintMinNumberForPattern("I");
        PrintMinNumberForPattern("DD");
        PrintMinNumberForPattern("II");
        PrintMinNumberForPattern("DIDI");
        PrintMinNumberForPattern("IIDDD");
        PrintMinNumberForPattern("DDIDDIID");
    }
}
 
// This code is contributed by Princi Singh


PHP


Javascript


C++
// C++ program to print minimum number that can be formed
// from a given sequence of Is and Ds
#include
using namespace std;
 
void printLeast(string arr)
{
    // min_avail represents the minimum number which is
    // still available for inserting in the output vector.
    // pos_of_I keeps track of the most recent index
    // where 'I' was encountered w.r.t the output vector
    int min_avail = 1, pos_of_I = 0;
 
    //vector to store the output
    vectorv;
 
    // cover the base cases
    if (arr[0]=='I')
    {
        v.push_back(1);
        v.push_back(2);
        min_avail = 3;
        pos_of_I = 1;
    }
    else
    {
        v.push_back(2);
        v.push_back(1);
        min_avail = 3;
        pos_of_I = 0;
    }
 
    // Traverse rest of the input
    for (int i=1; i


Java
// Java program to print minimum number that can be formed
// from a given sequence of Is and Ds
import java.io.*;
import java.util.*;
public class GFG {
 
       static void printLeast(String arr)
       {
              // min_avail represents the minimum number which is
              // still available for inserting in the output vector.
              // pos_of_I keeps track of the most recent index
              // where 'I' was encountered w.r.t the output vector
              int min_avail = 1, pos_of_I = 0;
 
              //vector to store the output
              ArrayList al = new ArrayList<>();
               
              // cover the base cases
              if (arr.charAt(0) == 'I')
              {
                  al.add(1);
                  al.add(2);
                  min_avail = 3;
                  pos_of_I = 1;
              }
 
              else
              {
                  al.add(2);
                  al.add(1);
                  min_avail = 3;
                  pos_of_I = 0;
              }
 
              // Traverse rest of the input
              for (int i = 1; i < arr.length(); i++)
              {
                   if (arr.charAt(i) == 'I')
                   {
                       al.add(min_avail);
                       min_avail++;
                       pos_of_I = i + 1;
                   }
                   else
                   {
                       al.add(al.get(i));
                       for (int j = pos_of_I; j <= i; j++)
                            al.set(j, al.get(j) + 1);
 
                       min_avail++;
                   }
              }
 
              // print the number
              for (int i = 0; i < al.size(); i++)
                   System.out.print(al.get(i) + " ");
              System.out.println();
       }
 
 
       // Driver code
       public static void main(String args[])
       {
              printLeast("IDID");
              printLeast("I");
              printLeast("DD");
              printLeast("II");
              printLeast("DIDI");
              printLeast("IIDDD");
              printLeast("DDIDDIID");
       }
}
// This code is contributed by rachana soma


Python3
# Python3 program to print minimum number
# that can be formed from a given sequence
# of Is and Ds
def printLeast(arr):
 
    # min_avail represents the minimum
    # number which is still available
    # for inserting in the output vector.
    # pos_of_I keeps track of the most
    # recent index where 'I' was
    # encountered w.r.t the output vector
    min_avail = 1
    pos_of_I = 0
 
    # Vector to store the output
    v = []
 
    # Cover the base cases
    if (arr[0] == 'I'):
        v.append(1)
        v.append(2)
         
        min_avail = 3
        pos_of_I = 1
    else:
        v.append(2)
        v.append(1)
         
        min_avail = 3
        pos_of_I = 0
 
    # Traverse rest of the input
    for i in range(1, len(arr)):
        if (arr[i] == 'I'):
            v.append(min_avail)
            min_avail += 1
            pos_of_I = i + 1
        else:
            v.append(v[i])
            for j in range(pos_of_I, i + 1):
                v[j] += 1
            min_avail += 1
             
    # Print the number
    print(*v, sep = ' ')
 
# Driver code
printLeast("IDID")
printLeast("I")
printLeast("DD")
printLeast("II")
printLeast("DIDI")
printLeast("IIDDD")
printLeast("DDIDDIID")
 
# This code is contributed by avanitrachhadiya2155


C#
// C# program to print minimum number that can be formed
// from a given sequence of Is and Ds
using System;
using System.Collections.Generic;
 
class GFG
{
     
static void printLeast(String arr)
{
    // min_avail represents the minimum number which is
    // still available for inserting in the output vector.
    // pos_of_I keeps track of the most recent index
    // where 'I' was encountered w.r.t the output vector
    int min_avail = 1, pos_of_I = 0;
 
    //vector to store the output
    List al = new List();
         
    // cover the base cases
    if (arr[0] == 'I')
    {
        al.Add(1);
        al.Add(2);
        min_avail = 3;
        pos_of_I = 1;
    }
 
    else
    {
        al.Add(2);
        al.Add(1);
        min_avail = 3;
        pos_of_I = 0;
    }
 
    // Traverse rest of the input
    for (int i = 1; i < arr.Length; i++)
    {
        if (arr[i] == 'I')
        {
            al.Add(min_avail);
            min_avail++;
            pos_of_I = i + 1;
        }
        else
        {
            al.Add(al[i]);
            for (int j = pos_of_I; j <= i; j++)
                al[j] = al[j] + 1;
 
            min_avail++;
        }
    }
 
    // print the number
    for (int i = 0; i < al.Count; i++)
        Console.Write(al[i] + " ");
    Console.WriteLine();
}
 
 
// Driver code
public static void Main(String []args)
{
    printLeast("IDID");
    printLeast("I");
    printLeast("DD");
    printLeast("II");
    printLeast("DIDI");
    printLeast("IIDDD");
    printLeast("DDIDDIID");
}
}
 
// This code is contributed by Rajput-Ji


Javascript


C++
// C++ program to print minimum number that can be formed
// from a given sequence of Is and Ds
#include 
using namespace std;
 
// Function to decode the given sequence to construct
// minimum number without repeated digits
void PrintMinNumberForPattern(string seq)
{
    // result store output string
    string result;
 
    // create an empty stack of integers
    stack stk;
 
    // run n+1 times where n is length of input sequence
    for (int i = 0; i <= seq.length(); i++)
    {
        // push number i+1 into the stack
        stk.push(i + 1);
 
        // if all characters of the input sequence are
        // processed or current character is 'I'
        // (increasing)
        if (i == seq.length() || seq[i] == 'I')
        {
            // run till stack is empty
            while (!stk.empty())
            {
                // remove top element from the stack and
                // add it to solution
                result += to_string(stk.top());
                result += " ";
                stk.pop();
            }
        }
    }
 
    cout << result << endl;
}
 
// main function
int main()
{
    PrintMinNumberForPattern("IDID");
    PrintMinNumberForPattern("I");
    PrintMinNumberForPattern("DD");
    PrintMinNumberForPattern("II");
    PrintMinNumberForPattern("DIDI");
    PrintMinNumberForPattern("IIDDD");
    PrintMinNumberForPattern("DDIDDIID");
    return 0;
}


Java
import java.util.Stack;
 
// Java program to print minimum number that can be formed
// from a given sequence of Is and Ds
class GFG {
 
// Function to decode the given sequence to construct
// minimum number without repeated digits
    static void PrintMinNumberForPattern(String seq) {
        // result store output string
        String result = "";
 
        // create an empty stack of integers
        Stack stk = new Stack();
 
        // run n+1 times where n is length of input sequence
        for (int i = 0; i <= seq.length(); i++) {
            // push number i+1 into the stack
            stk.push(i + 1);
 
            // if all characters of the input sequence are
            // processed or current character is 'I'
            // (increasing)
            if (i == seq.length() || seq.charAt(i) == 'I') {
                // run till stack is empty
                while (!stk.empty()) {
                    // remove top element from the stack and
                    // add it to solution
                    result += String.valueOf(stk.peek());
                    result += " ";
                    stk.pop();
                }
            }
        }
 
        System.out.println(result);
    }
 
// main function
    public static void main(String[] args) {
        PrintMinNumberForPattern("IDID");
        PrintMinNumberForPattern("I");
        PrintMinNumberForPattern("DD");
        PrintMinNumberForPattern("II");
        PrintMinNumberForPattern("DIDI");
        PrintMinNumberForPattern("IIDDD");
        PrintMinNumberForPattern("DDIDDIID");
    }
}
// This code is contributed by PrinciRaj1992


Python3
# Python3 program to print minimum
# number that can be formed from a
# given sequence of Is and Ds
def PrintMinNumberForPattern(Strr):
     
    # Take a List to work as Stack
    stack = []
 
    # String for storing result
    res = ''
 
    # run n+1 times where n is length
    # of input sequence, As length of
    # result string is always 1 greater
    for i in range(len(Strr) + 1):
 
        # Push number i+1 into the stack
        stack.append(i + 1)
 
        # If all characters of the input
        # sequence are processed or current
        # character is 'I
        if (i == len(Strr) or Strr[i] == 'I'):
 
            # Run While Loop Until stack is empty
            while len(stack) > 0:
                 
                # pop the element on top of stack
                # And store it in result String
                res += str(stack.pop())
                res += ' '
                 
    # Print the result
    print(res)
 
# Driver Code
PrintMinNumberForPattern("IDID")
PrintMinNumberForPattern("I")
PrintMinNumberForPattern("DD")
PrintMinNumberForPattern("II")
PrintMinNumberForPattern("DIDI")
PrintMinNumberForPattern("IIDDD")
PrintMinNumberForPattern("DDIDDIID")
 
# This code is contributed by AyushManglani


C#
// C# program to print minimum number that can be formed
// from a given sequence of Is and Ds
using System;
using System.Collections;
public class GFG {
  
// Function to decode the given sequence to construct
// minimum number without repeated digits
    static void PrintMinNumberForPattern(String seq) {
        // result store output string
        String result = "";
  
        // create an empty stack of integers
        Stack stk = new Stack();
  
        // run n+1 times where n is length of input sequence
        for (int i = 0; i <= seq.Length; i++) {
            // push number i+1 into the stack
            stk.Push(i + 1);
  
            // if all characters of the input sequence are
            // processed or current character is 'I'
            // (increasing)
            if (i == seq.Length || seq[i] == 'I') {
                // run till stack is empty
                while (stk.Count!=0) {
                    // remove top element from the stack and
                    // add it to solution
                    result += String.Join("",stk.Peek());
                    result += " ";
                    stk.Pop();
                }
            }
        }
  
        Console.WriteLine(result);
    }
  
// main function
    public static void Main() {
        PrintMinNumberForPattern("IDID");
        PrintMinNumberForPattern("I");
        PrintMinNumberForPattern("DD");
        PrintMinNumberForPattern("II");
        PrintMinNumberForPattern("DIDI");
        PrintMinNumberForPattern("IIDDD");
        PrintMinNumberForPattern("DDIDDIID");
    }
}
// This code is contributed by 29AjayKumar


Javascript


C++
// C++ program of above approach
#include 
using namespace std;
   
// Returns minimum number made from given sequence without repeating digits
string getMinNumberForPattern(string seq)
{
    int n = seq.length();
 
    if (n >= 9)
        return "-1";
 
    string result(n+1, ' ');
 
    int count = 1; 
 
    // The loop runs for each input character as well as
    // one additional time for assigning rank to remaining characters
    for (int i = 0; i <= n; i++)
    {
        if (i == n || seq[i] == 'I')
        {
            for (int j = i - 1 ; j >= -1 ; j--)
            {
                result[j + 1] = '0' + count++;
                if(j >= 0 && seq[j] == 'I')
                    break;
            }
        }
    }
    return result;
}
   
// main function
int main()
{
    string inputs[] = {"IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID"};
 
    for (string input : inputs)
    {
        cout << getMinNumberForPattern(input) << "\n";
    }
    return 0;
}


Java
// Java program of above approach
import java.io.IOException;
 
public class Test
{
    // Returns minimum number made from given sequence without repeating digits
    static String getMinNumberForPattern(String seq)
    {
        int n = seq.length();
 
        if (n >= 9)
            return "-1";
 
        char result[] = new char[n + 1];
 
        int count = 1;
 
        // The loop runs for each input character as well as
        // one additional time for assigning rank to each remaining characters
        for (int i = 0; i <= n; i++)
        {
            if (i == n || seq.charAt(i) == 'I')
            {
                for (int j = i - 1; j >= -1; j--)
                {
                    result[j + 1] = (char) ((int) '0' + count++);
                    if (j >= 0 && seq.charAt(j) == 'I')
                        break;
                }
            }
        }
        return new String(result);
    }
     
    public static void main(String[] args) throws IOException
    {
        String inputs[] = { "IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID" };
 
        for(String input : inputs)
        {
            System.out.println(getMinNumberForPattern(input));
        }
    }
}


Python3
# Python3 program of above approach
     
# Returns minimum number made from
# given sequence without repeating digits
def getMinNumberForPattern(seq):
    n = len(seq)
 
    if (n >= 9):
        return "-1"
 
    result = [None] * (n + 1)
 
    count = 1
 
    # The loop runs for each input character
    # as well as one additional time for
    # assigning rank to remaining characters
    for i in range(n + 1):
        if (i == n or seq[i] == 'I'):
            for j in range(i - 1, -2, -1):
                result[j + 1] = int('0' + str(count))
                count += 1
                if(j >= 0 and seq[j] == 'I'):
                    break
    return result
     
# Driver Code
if __name__ == '__main__':
    inputs = ["IDID", "I", "DD", "II",
              "DIDI", "IIDDD", "DDIDDIID"]
    for Input in inputs:
        print(*(getMinNumberForPattern(Input)))
 
# This code is contributed by PranchalK


C#
// C# program of above approach
using System;
class GFG
{
     
// Returns minimum number made from given
// sequence without repeating digits
static String getMinNumberForPattern(String seq)
{
    int n = seq.Length;
 
    if (n >= 9)
        return "-1";
 
    char []result = new char[n + 1];
 
    int count = 1;
 
    // The loop runs for each input character
    // as well as one additional time for
    // assigning rank to each remaining characters
    for (int i = 0; i <= n; i++)
    {
        if (i == n || seq[i] == 'I')
        {
            for (int j = i - 1; j >= -1; j--)
            {
                result[j + 1] = (char) ((int) '0' + count++);
                if (j >= 0 && seq[j] == 'I')
                    break;
            }
        }
    }
    return new String(result);
}
 
// Driver Code
public static void Main()
{
    String []inputs = { "IDID", "I", "DD", "II",
                        "DIDI", "IIDDD", "DDIDDIID" };
 
    foreach(String input in inputs)
    {
        Console.WriteLine(getMinNumberForPattern(input));
    }
}
}
 
// This code is contributed by Rajput-Ji


Javascript


Python3
# Python implementation of the above approach
 
def didi_seq_gen(s: str):
    '''
    :param s: a seq consisting only of 'D'
    and 'I' chars. D is for decreasing and
    I for increasing
    :return: digits from 1-9 that fit the str.
    The number they repr should the min
    such number
    :rtype: str
    example : for seq DII -> 2134
    '''
    if not s or len(s) <= 0:
        return ""
    base_list = ["1"]
    for i in range(1, len(s) + 1):
        base_list.append(f'{i + 1}')
 
    last_D = -1
    for i in range(1, len(base_list)):
        if s[i - 1] == 'D':
            if last_D < 0:
                last_D = i - 1
            v = base_list[i]
            del base_list[i]
            base_list.insert(last_D, v)
        else:
            last_D = -1
 
    return base_list
 
# Driver Code
# Function call
print(didi_seq_gen("IDID"))
print(didi_seq_gen("I"))
print(didi_seq_gen("DD"))
print(didi_seq_gen("II"))
print(didi_seq_gen("DIDI"))
print(didi_seq_gen("IIDDD"))
print(didi_seq_gen("DDIDDIID" ))


C++
// This code illustrates to find minimum number following
// pattern with optimized space and modular code.
#include 
using namespace std;
 
 
// This function returns minimum number following
// pattern of increasing or decreasing sequence.
string findMinNumberPattern(string str)
{
    string ans = ""; // Minimum number following pattern
 
    int i = 0;
    int cur = 1; // cur val following pattern
    int dCount = 0; // Count of char 'D'
    while (i < str.length()) {
 
        char ch = str[i];
 
        // If 1st ch == 'I', incr and add to ans
        if (i == 0 && ch == 'I') {
            ans += to_string(cur);
            cur++;
        }
 
        // If cur char == 'D',
        // incr dCount as well, since we always
        // start counting for dCount from i+1
        if (ch == 'D') {
            dCount++;
        }
 
        int j = i + 1; // Count 'D' from i+1 index
        while (j < str.length()
               && str[j] == 'D') {
            dCount++;
            j++;
        }
 
        int k = dCount;  // Store dCount
        while (dCount >= 0) {
            ans += to_string(cur + dCount);
            dCount--;
        }
 
        cur += (k + 1); // Manages next cur val
        dCount = 0;
        i = j;
    }
 
    return ans;
}
     
int main()
{
    cout << (findMinNumberPattern("DIDID")) << endl;
    cout << (findMinNumberPattern("DIDIII")) << endl;
    cout << (findMinNumberPattern("DDDIIDI")) << endl;
    cout << (findMinNumberPattern("IDIDIID")) << endl;
    cout << (findMinNumberPattern("DIIDIDD")) << endl;
    cout << (findMinNumberPattern("IIDIDDD")) << endl;
 
    return 0;
}
 
// This code is contributed by suresh07.


Java
/*package whatever //do not write package name here */
 
// This code illustrates to find minimum number following
// pattern with optimized space and modular code.
 
import java.io.*;
 
class GFG {
 
    // This function returns minimum number following
    // pattern of increasing or decreasing sequence.
    public static String findMinNumberPattern(String str)
    {
        String ans = ""; // Minimum number following pattern
 
        int i = 0;
        int cur = 1; // cur val following pattern
        int dCount = 0; // Count of char 'D'
        while (i < str.length()) {
 
            char ch = str.charAt(i);
 
            // If 1st ch == 'I', incr and add to ans
            if (i == 0 && ch == 'I') {
                ans += cur;
                cur++;
            }
 
            // If cur char == 'D',
            // incr dCount as well, since we always
            // start counting for dCount from i+1
            if (ch == 'D') {
                dCount++;
            }
 
            int j = i + 1; // Count 'D' from i+1 index
            while (j < str.length()
                   && str.charAt(j) == 'D') {
                dCount++;
                j++;
            }
 
            int k = dCount;  // Store dCount
            while (dCount >= 0) {
                ans += (cur + dCount);
                dCount--;
            }
 
            cur += (k + 1); // Manages next cur val
            dCount = 0;
            i = j;
        }
 
        return ans;
    }
    public static void main(String[] args)
    {
        System.out.println(findMinNumberPattern("DIDID"));
        System.out.println(findMinNumberPattern("DIDIII"));
        System.out.println(findMinNumberPattern("DDDIIDI"));
        System.out.println(findMinNumberPattern("IDIDIID"));
        System.out.println(findMinNumberPattern("DIIDIDD"));
        System.out.println(findMinNumberPattern("IIDIDDD"));
    }
}
 
// This code is contributed by Arun M


Python3
# This code illustrates to find minimum number following
# pattern with optimized space and modular code.
 
# This function returns minimum number following
# pattern of increasing or decreasing sequence.
def findMinNumberPattern(Str):
 
    ans = "" # Minimum number following pattern
 
    i = 0
    cur = 1 # cur val following pattern
    dCount = 0 # Count of char 'D'
    while (i < len(Str)) :
 
        ch = Str[i]
 
        # If 1st ch == 'I', incr and add to ans
        if (i == 0 and ch == 'I') :
            ans += str(cur)
            cur+=1
 
        # If cur char == 'D',
        # incr dCount as well, since we always
        # start counting for dCount from i+1
        if (ch == 'D') :
            dCount+=1
         
 
        j = i + 1 # Count 'D' from i+1 index
        while (j < len(Str) and Str[j] == 'D') :
            dCount+=1
            j+=1
         
 
        k = dCount  # Store dCount
        while (dCount >= 0) :
            ans += str(cur + dCount)
            dCount-=1
         
 
        cur += (k + 1) # Manages next cur val
        dCount = 0
        i = j
 
    return ans
     
print(findMinNumberPattern("DIDID"))
print(findMinNumberPattern("DIDIII"))
print(findMinNumberPattern("DDDIIDI"))
print(findMinNumberPattern("IDIDIID"))
print(findMinNumberPattern("DIIDIDD"))
print(findMinNumberPattern("IIDIDDD"))
 
# This code is contributed by mukesh07.


C#
// This code illustrates to find minimum number following
// pattern with optimized space and modular code.
using System;
class GFG {
     
    // This function returns minimum number following
    // pattern of increasing or decreasing sequence.
    public static string findMinNumberPattern(string str)
    {
        string ans = ""; // Minimum number following pattern
  
        int i = 0;
        int cur = 1; // cur val following pattern
        int dCount = 0; // Count of char 'D'
        while (i < str.Length) {
  
            char ch = str[i];
  
            // If 1st ch == 'I', incr and add to ans
            if (i == 0 && ch == 'I') {
                ans += cur;
                cur++;
            }
  
            // If cur char == 'D',
            // incr dCount as well, since we always
            // start counting for dCount from i+1
            if (ch == 'D') {
                dCount++;
            }
  
            int j = i + 1; // Count 'D' from i+1 index
            while (j < str.Length
                   && str[j] == 'D') {
                dCount++;
                j++;
            }
  
            int k = dCount;  // Store dCount
            while (dCount >= 0) {
                ans += (cur + dCount);
                dCount--;
            }
  
            cur += (k + 1); // Manages next cur val
            dCount = 0;
            i = j;
        }
  
        return ans;
    }
     
  static void Main() {
    Console.WriteLine(findMinNumberPattern("DIDID"));
    Console.WriteLine(findMinNumberPattern("DIDIII"));
    Console.WriteLine(findMinNumberPattern("DDDIIDI"));
    Console.WriteLine(findMinNumberPattern("IDIDIID"));
    Console.WriteLine(findMinNumberPattern("DIIDIDD"));
    Console.WriteLine(findMinNumberPattern("IIDIDDD"));
  }
}
 
// This code is contributed by mukesh07.


Javascript


输出:

1 3 2 5 4
 1 2
 3 2 1
 1 2 3
 2 1 4 3 5
 1 2 6 5 4 3
 3 2 1 6 5 4 7 9 8

Swapnil Trambake 建议使用此解决方案。

替代解决方案:
让我们在最小数量的情况下观察一些事实:

  • 数字不能重复,因此输出最多可以有 9 个数字。
  • 为了形成最小数字,在输出的每个索引处,我们对可以放置在该索引处的最小数字感兴趣。

这个想法是迭代整个输入数组,跟踪可以放置在输出的那个位置的最小数字(1-9)。

棘手的部分当然是在索引不是 0 处遇到“D”时。在这种情况下,我们必须跟踪“D”左侧最近的“I”,并将输出向量中的每个数字增加 1。 “我”和“D”。
我们涵盖以下基本情况:

  • 如果输入的第一个字符是“I”,那么我们在输出向量中附加 1 和 2,并且最小可用数字设置为 3。最近的“I”的索引设置为 1。
  • 如果输入的第一个字符是“D”,那么我们在输出向量中附加 2 和 1,最小可用数设置为 3,最近的“I”的索引设置为 0。

现在我们从索引 1 迭代输入字符串直到它的结尾,并且:

  • 如果扫描的字符是 'I' ,则将一个尚未使用的最小值附加到输出向量中。我们增加 minimum no 的值。可用并且最近的“我”的索引也被更新。
  • 如果扫描的字符是输入数组索引 i 处的“D”,我们将输出向量中的第 i 个元素附加到输出中,并跟踪“D”左侧最近的“I”并将输出向量中的每个数字加 1在“I”和“D”之间。

以下是相同的程序:

C++

// C++ program to print minimum number that can be formed
// from a given sequence of Is and Ds
#include
using namespace std;
 
void printLeast(string arr)
{
    // min_avail represents the minimum number which is
    // still available for inserting in the output vector.
    // pos_of_I keeps track of the most recent index
    // where 'I' was encountered w.r.t the output vector
    int min_avail = 1, pos_of_I = 0;
 
    //vector to store the output
    vectorv;
 
    // cover the base cases
    if (arr[0]=='I')
    {
        v.push_back(1);
        v.push_back(2);
        min_avail = 3;
        pos_of_I = 1;
    }
    else
    {
        v.push_back(2);
        v.push_back(1);
        min_avail = 3;
        pos_of_I = 0;
    }
 
    // Traverse rest of the input
    for (int i=1; i

Java

// Java program to print minimum number that can be formed
// from a given sequence of Is and Ds
import java.io.*;
import java.util.*;
public class GFG {
 
       static void printLeast(String arr)
       {
              // min_avail represents the minimum number which is
              // still available for inserting in the output vector.
              // pos_of_I keeps track of the most recent index
              // where 'I' was encountered w.r.t the output vector
              int min_avail = 1, pos_of_I = 0;
 
              //vector to store the output
              ArrayList al = new ArrayList<>();
               
              // cover the base cases
              if (arr.charAt(0) == 'I')
              {
                  al.add(1);
                  al.add(2);
                  min_avail = 3;
                  pos_of_I = 1;
              }
 
              else
              {
                  al.add(2);
                  al.add(1);
                  min_avail = 3;
                  pos_of_I = 0;
              }
 
              // Traverse rest of the input
              for (int i = 1; i < arr.length(); i++)
              {
                   if (arr.charAt(i) == 'I')
                   {
                       al.add(min_avail);
                       min_avail++;
                       pos_of_I = i + 1;
                   }
                   else
                   {
                       al.add(al.get(i));
                       for (int j = pos_of_I; j <= i; j++)
                            al.set(j, al.get(j) + 1);
 
                       min_avail++;
                   }
              }
 
              // print the number
              for (int i = 0; i < al.size(); i++)
                   System.out.print(al.get(i) + " ");
              System.out.println();
       }
 
 
       // Driver code
       public static void main(String args[])
       {
              printLeast("IDID");
              printLeast("I");
              printLeast("DD");
              printLeast("II");
              printLeast("DIDI");
              printLeast("IIDDD");
              printLeast("DDIDDIID");
       }
}
// This code is contributed by rachana soma

Python3

# Python3 program to print minimum number
# that can be formed from a given sequence
# of Is and Ds
def printLeast(arr):
 
    # min_avail represents the minimum
    # number which is still available
    # for inserting in the output vector.
    # pos_of_I keeps track of the most
    # recent index where 'I' was
    # encountered w.r.t the output vector
    min_avail = 1
    pos_of_I = 0
 
    # Vector to store the output
    v = []
 
    # Cover the base cases
    if (arr[0] == 'I'):
        v.append(1)
        v.append(2)
         
        min_avail = 3
        pos_of_I = 1
    else:
        v.append(2)
        v.append(1)
         
        min_avail = 3
        pos_of_I = 0
 
    # Traverse rest of the input
    for i in range(1, len(arr)):
        if (arr[i] == 'I'):
            v.append(min_avail)
            min_avail += 1
            pos_of_I = i + 1
        else:
            v.append(v[i])
            for j in range(pos_of_I, i + 1):
                v[j] += 1
            min_avail += 1
             
    # Print the number
    print(*v, sep = ' ')
 
# Driver code
printLeast("IDID")
printLeast("I")
printLeast("DD")
printLeast("II")
printLeast("DIDI")
printLeast("IIDDD")
printLeast("DDIDDIID")
 
# This code is contributed by avanitrachhadiya2155

C#

// C# program to print minimum number that can be formed
// from a given sequence of Is and Ds
using System;
using System.Collections.Generic;
 
class GFG
{
     
static void printLeast(String arr)
{
    // min_avail represents the minimum number which is
    // still available for inserting in the output vector.
    // pos_of_I keeps track of the most recent index
    // where 'I' was encountered w.r.t the output vector
    int min_avail = 1, pos_of_I = 0;
 
    //vector to store the output
    List al = new List();
         
    // cover the base cases
    if (arr[0] == 'I')
    {
        al.Add(1);
        al.Add(2);
        min_avail = 3;
        pos_of_I = 1;
    }
 
    else
    {
        al.Add(2);
        al.Add(1);
        min_avail = 3;
        pos_of_I = 0;
    }
 
    // Traverse rest of the input
    for (int i = 1; i < arr.Length; i++)
    {
        if (arr[i] == 'I')
        {
            al.Add(min_avail);
            min_avail++;
            pos_of_I = i + 1;
        }
        else
        {
            al.Add(al[i]);
            for (int j = pos_of_I; j <= i; j++)
                al[j] = al[j] + 1;
 
            min_avail++;
        }
    }
 
    // print the number
    for (int i = 0; i < al.Count; i++)
        Console.Write(al[i] + " ");
    Console.WriteLine();
}
 
 
// Driver code
public static void Main(String []args)
{
    printLeast("IDID");
    printLeast("I");
    printLeast("DD");
    printLeast("II");
    printLeast("DIDI");
    printLeast("IIDDD");
    printLeast("DDIDDIID");
}
}
 
// This code is contributed by Rajput-Ji

Javascript


输出
1 3 2 5 4 
1 2 
3 2 1 
1 2 3 
2 1 4 3 5 
1 2 6 5 4 3 
3 2 1 6 5 4 7 9 8 

该解决方案由 Ashutosh Kumar 提出。方法三
我们可以这样,当我们遇到 I 时,我们得到的数字是升序的,但是如果我们遇到 'D',我们希望得到的数字是降序的。输出字符串的长度总是比输入字符串。所以循环是从 0 到字符串的长度。我们必须从 1-9 取数字,所以我们总是将 (i+1) 压入我们的堆栈。然后我们检查指定索引处的结果字符是什么。因此,将有两种情况如下:-

情况 1:如果遇到 I 或者我们在输入字符串的最后一个字符处,则从堆栈中弹出并将其添加到输出字符串的末尾,直到堆栈为空。

情况 2:如果我们遇到了 D,那么我们希望数字按降序排列。所以我们只需将 (i+1) 推入我们的堆栈。

C++

// C++ program to print minimum number that can be formed
// from a given sequence of Is and Ds
#include 
using namespace std;
 
// Function to decode the given sequence to construct
// minimum number without repeated digits
void PrintMinNumberForPattern(string seq)
{
    // result store output string
    string result;
 
    // create an empty stack of integers
    stack stk;
 
    // run n+1 times where n is length of input sequence
    for (int i = 0; i <= seq.length(); i++)
    {
        // push number i+1 into the stack
        stk.push(i + 1);
 
        // if all characters of the input sequence are
        // processed or current character is 'I'
        // (increasing)
        if (i == seq.length() || seq[i] == 'I')
        {
            // run till stack is empty
            while (!stk.empty())
            {
                // remove top element from the stack and
                // add it to solution
                result += to_string(stk.top());
                result += " ";
                stk.pop();
            }
        }
    }
 
    cout << result << endl;
}
 
// main function
int main()
{
    PrintMinNumberForPattern("IDID");
    PrintMinNumberForPattern("I");
    PrintMinNumberForPattern("DD");
    PrintMinNumberForPattern("II");
    PrintMinNumberForPattern("DIDI");
    PrintMinNumberForPattern("IIDDD");
    PrintMinNumberForPattern("DDIDDIID");
    return 0;
}

Java

import java.util.Stack;
 
// Java program to print minimum number that can be formed
// from a given sequence of Is and Ds
class GFG {
 
// Function to decode the given sequence to construct
// minimum number without repeated digits
    static void PrintMinNumberForPattern(String seq) {
        // result store output string
        String result = "";
 
        // create an empty stack of integers
        Stack stk = new Stack();
 
        // run n+1 times where n is length of input sequence
        for (int i = 0; i <= seq.length(); i++) {
            // push number i+1 into the stack
            stk.push(i + 1);
 
            // if all characters of the input sequence are
            // processed or current character is 'I'
            // (increasing)
            if (i == seq.length() || seq.charAt(i) == 'I') {
                // run till stack is empty
                while (!stk.empty()) {
                    // remove top element from the stack and
                    // add it to solution
                    result += String.valueOf(stk.peek());
                    result += " ";
                    stk.pop();
                }
            }
        }
 
        System.out.println(result);
    }
 
// main function
    public static void main(String[] args) {
        PrintMinNumberForPattern("IDID");
        PrintMinNumberForPattern("I");
        PrintMinNumberForPattern("DD");
        PrintMinNumberForPattern("II");
        PrintMinNumberForPattern("DIDI");
        PrintMinNumberForPattern("IIDDD");
        PrintMinNumberForPattern("DDIDDIID");
    }
}
// This code is contributed by PrinciRaj1992

Python3

# Python3 program to print minimum
# number that can be formed from a
# given sequence of Is and Ds
def PrintMinNumberForPattern(Strr):
     
    # Take a List to work as Stack
    stack = []
 
    # String for storing result
    res = ''
 
    # run n+1 times where n is length
    # of input sequence, As length of
    # result string is always 1 greater
    for i in range(len(Strr) + 1):
 
        # Push number i+1 into the stack
        stack.append(i + 1)
 
        # If all characters of the input
        # sequence are processed or current
        # character is 'I
        if (i == len(Strr) or Strr[i] == 'I'):
 
            # Run While Loop Until stack is empty
            while len(stack) > 0:
                 
                # pop the element on top of stack
                # And store it in result String
                res += str(stack.pop())
                res += ' '
                 
    # Print the result
    print(res)
 
# Driver Code
PrintMinNumberForPattern("IDID")
PrintMinNumberForPattern("I")
PrintMinNumberForPattern("DD")
PrintMinNumberForPattern("II")
PrintMinNumberForPattern("DIDI")
PrintMinNumberForPattern("IIDDD")
PrintMinNumberForPattern("DDIDDIID")
 
# This code is contributed by AyushManglani

C#

// C# program to print minimum number that can be formed
// from a given sequence of Is and Ds
using System;
using System.Collections;
public class GFG {
  
// Function to decode the given sequence to construct
// minimum number without repeated digits
    static void PrintMinNumberForPattern(String seq) {
        // result store output string
        String result = "";
  
        // create an empty stack of integers
        Stack stk = new Stack();
  
        // run n+1 times where n is length of input sequence
        for (int i = 0; i <= seq.Length; i++) {
            // push number i+1 into the stack
            stk.Push(i + 1);
  
            // if all characters of the input sequence are
            // processed or current character is 'I'
            // (increasing)
            if (i == seq.Length || seq[i] == 'I') {
                // run till stack is empty
                while (stk.Count!=0) {
                    // remove top element from the stack and
                    // add it to solution
                    result += String.Join("",stk.Peek());
                    result += " ";
                    stk.Pop();
                }
            }
        }
  
        Console.WriteLine(result);
    }
  
// main function
    public static void Main() {
        PrintMinNumberForPattern("IDID");
        PrintMinNumberForPattern("I");
        PrintMinNumberForPattern("DD");
        PrintMinNumberForPattern("II");
        PrintMinNumberForPattern("DIDI");
        PrintMinNumberForPattern("IIDDD");
        PrintMinNumberForPattern("DDIDDIID");
    }
}
// This code is contributed by 29AjayKumar

Javascript


输出:

1 3 2 5 4 
1 2 
3 2 1 
1 2 3 
2 1 4 3 5 
1 2 6 5 4 3 
3 2 1 6 5 4 7 9 8

时间复杂度: O(n)
辅助空间: O(n)
此方法由Roshni Agarwal提供。

方法4(使用两个指针)
观察

  1. 由于我们必须找到一个不重复数字的最小数字,因此输出的最大长度可以是 9(每个 1-9 位使用一次)
  2. 输出的长度将恰好比输入长度大一。
  3. 这个想法是遍历字符串并在当前字符为“I”或字符串结束时执行以下操作。
    1. 从 current-1 到 'I' 的下一个左侧索引(或达到起始索引),按递增顺序为每个元素分配计数。
    2. 将计数增加 1。
Input  :  IDID
Output : 13254

Input  :  I
Output : 12

Input  :  DD
Output : 321

Input  :  II
Output : 123

Input  :  DIDI
Output : 21435

Input  :  IIDDD
Output : 126543

Input  :  DDIDDIID
Output : 321654798

以下是上述方法的实现:

C++

// C++ program of above approach
#include 
using namespace std;
   
// Returns minimum number made from given sequence without repeating digits
string getMinNumberForPattern(string seq)
{
    int n = seq.length();
 
    if (n >= 9)
        return "-1";
 
    string result(n+1, ' ');
 
    int count = 1; 
 
    // The loop runs for each input character as well as
    // one additional time for assigning rank to remaining characters
    for (int i = 0; i <= n; i++)
    {
        if (i == n || seq[i] == 'I')
        {
            for (int j = i - 1 ; j >= -1 ; j--)
            {
                result[j + 1] = '0' + count++;
                if(j >= 0 && seq[j] == 'I')
                    break;
            }
        }
    }
    return result;
}
   
// main function
int main()
{
    string inputs[] = {"IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID"};
 
    for (string input : inputs)
    {
        cout << getMinNumberForPattern(input) << "\n";
    }
    return 0;
}

Java

// Java program of above approach
import java.io.IOException;
 
public class Test
{
    // Returns minimum number made from given sequence without repeating digits
    static String getMinNumberForPattern(String seq)
    {
        int n = seq.length();
 
        if (n >= 9)
            return "-1";
 
        char result[] = new char[n + 1];
 
        int count = 1;
 
        // The loop runs for each input character as well as
        // one additional time for assigning rank to each remaining characters
        for (int i = 0; i <= n; i++)
        {
            if (i == n || seq.charAt(i) == 'I')
            {
                for (int j = i - 1; j >= -1; j--)
                {
                    result[j + 1] = (char) ((int) '0' + count++);
                    if (j >= 0 && seq.charAt(j) == 'I')
                        break;
                }
            }
        }
        return new String(result);
    }
     
    public static void main(String[] args) throws IOException
    {
        String inputs[] = { "IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID" };
 
        for(String input : inputs)
        {
            System.out.println(getMinNumberForPattern(input));
        }
    }
}

Python3

# Python3 program of above approach
     
# Returns minimum number made from
# given sequence without repeating digits
def getMinNumberForPattern(seq):
    n = len(seq)
 
    if (n >= 9):
        return "-1"
 
    result = [None] * (n + 1)
 
    count = 1
 
    # The loop runs for each input character
    # as well as one additional time for
    # assigning rank to remaining characters
    for i in range(n + 1):
        if (i == n or seq[i] == 'I'):
            for j in range(i - 1, -2, -1):
                result[j + 1] = int('0' + str(count))
                count += 1
                if(j >= 0 and seq[j] == 'I'):
                    break
    return result
     
# Driver Code
if __name__ == '__main__':
    inputs = ["IDID", "I", "DD", "II",
              "DIDI", "IIDDD", "DDIDDIID"]
    for Input in inputs:
        print(*(getMinNumberForPattern(Input)))
 
# This code is contributed by PranchalK

C#

// C# program of above approach
using System;
class GFG
{
     
// Returns minimum number made from given
// sequence without repeating digits
static String getMinNumberForPattern(String seq)
{
    int n = seq.Length;
 
    if (n >= 9)
        return "-1";
 
    char []result = new char[n + 1];
 
    int count = 1;
 
    // The loop runs for each input character
    // as well as one additional time for
    // assigning rank to each remaining characters
    for (int i = 0; i <= n; i++)
    {
        if (i == n || seq[i] == 'I')
        {
            for (int j = i - 1; j >= -1; j--)
            {
                result[j + 1] = (char) ((int) '0' + count++);
                if (j >= 0 && seq[j] == 'I')
                    break;
            }
        }
    }
    return new String(result);
}
 
// Driver Code
public static void Main()
{
    String []inputs = { "IDID", "I", "DD", "II",
                        "DIDI", "IIDDD", "DDIDDIID" };
 
    foreach(String input in inputs)
    {
        Console.WriteLine(getMinNumberForPattern(input));
    }
}
}
 
// This code is contributed by Rajput-Ji

Javascript


输出
13254
12
321
123
21435
126543
321654798

方法5(从最小的开始)

从最小的数字开始作为答案,并在遇到D时不断移动数字。
无需遍历索引。
按照以下步骤,

  1. len(s)+1的最小数字开始(比如DI,“123”开始)
  2. 现在,从第二个数字(索引 1)和第一个字符( D )开始,迭代直到数字列表的末尾,跟踪D序列中的第一个D
    1. 当我们遇到D
      将当前索引处的数字移动到序列中的第一个 D
    2. 当我们遇到一个
      重置 D 的最后一个已知位置。当数字正确放置时,没有什么可以移动的(截至目前……

下面是上述方法的实现:

Python3

# Python implementation of the above approach
 
def didi_seq_gen(s: str):
    '''
    :param s: a seq consisting only of 'D'
    and 'I' chars. D is for decreasing and
    I for increasing
    :return: digits from 1-9 that fit the str.
    The number they repr should the min
    such number
    :rtype: str
    example : for seq DII -> 2134
    '''
    if not s or len(s) <= 0:
        return ""
    base_list = ["1"]
    for i in range(1, len(s) + 1):
        base_list.append(f'{i + 1}')
 
    last_D = -1
    for i in range(1, len(base_list)):
        if s[i - 1] == 'D':
            if last_D < 0:
                last_D = i - 1
            v = base_list[i]
            del base_list[i]
            base_list.insert(last_D, v)
        else:
            last_D = -1
 
    return base_list
 
# Driver Code
# Function call
print(didi_seq_gen("IDID"))
print(didi_seq_gen("I"))
print(didi_seq_gen("DD"))
print(didi_seq_gen("II"))
print(didi_seq_gen("DIDI"))
print(didi_seq_gen("IIDDD"))
print(didi_seq_gen("DDIDDIID" ))
输出
['1', '3', '2', '5', '4']
['1', '2']
['3', '2', '1']
['1', '2', '3']
['2', '1', '4', '3', '5']
['1', '2', '6', '5', '4', '3']
['3', '2', '1', '6', '5', '4', '7', '9', '8']

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

方法6:(方法1的空间优化和模块化代码)

例子:

Input: "DDDD"
Output: "432156"

For input 1, pattern is like,     D -> D -> D -> D
                               5   4    3    2    1
                               
Input: "DDDII"
Output: "432156"

For input 2, pattern is like,     D -> D -> D -> I -> I
                               4   3    2     1      5       6


Input: "IIDIDIII"
Output: "124365789"

For input 3, pattern is like,     I -> I -> D -> I -> D -> I -> I -> I
                               1    2   4    3    6    5    7    8    9    

方法:

  • 想想如果字符串只包含字符'I'增加,那么你可以打印并继续增加没有任何问题。
  • 现在想想如果字符串只包含增加的字符'D',那么你必须以某种方式从初始点获取数字'D'字符,这样你就可以从'D'的总数开始并通过递减来打印。
  • 问题是当您在字符“I”之后遇到字符“D”时。在这里,您必须以某种方式计算“D”以获得“D”的下一个可能递减开始,然后通过递减打印,直到遇到所有“D”。
  • 在这种方法中,与空间优化版本的方法 1 相比,代码变得更加模块化。

C++

// This code illustrates to find minimum number following
// pattern with optimized space and modular code.
#include 
using namespace std;
 
 
// This function returns minimum number following
// pattern of increasing or decreasing sequence.
string findMinNumberPattern(string str)
{
    string ans = ""; // Minimum number following pattern
 
    int i = 0;
    int cur = 1; // cur val following pattern
    int dCount = 0; // Count of char 'D'
    while (i < str.length()) {
 
        char ch = str[i];
 
        // If 1st ch == 'I', incr and add to ans
        if (i == 0 && ch == 'I') {
            ans += to_string(cur);
            cur++;
        }
 
        // If cur char == 'D',
        // incr dCount as well, since we always
        // start counting for dCount from i+1
        if (ch == 'D') {
            dCount++;
        }
 
        int j = i + 1; // Count 'D' from i+1 index
        while (j < str.length()
               && str[j] == 'D') {
            dCount++;
            j++;
        }
 
        int k = dCount;  // Store dCount
        while (dCount >= 0) {
            ans += to_string(cur + dCount);
            dCount--;
        }
 
        cur += (k + 1); // Manages next cur val
        dCount = 0;
        i = j;
    }
 
    return ans;
}
     
int main()
{
    cout << (findMinNumberPattern("DIDID")) << endl;
    cout << (findMinNumberPattern("DIDIII")) << endl;
    cout << (findMinNumberPattern("DDDIIDI")) << endl;
    cout << (findMinNumberPattern("IDIDIID")) << endl;
    cout << (findMinNumberPattern("DIIDIDD")) << endl;
    cout << (findMinNumberPattern("IIDIDDD")) << endl;
 
    return 0;
}
 
// This code is contributed by suresh07.

Java

/*package whatever //do not write package name here */
 
// This code illustrates to find minimum number following
// pattern with optimized space and modular code.
 
import java.io.*;
 
class GFG {
 
    // This function returns minimum number following
    // pattern of increasing or decreasing sequence.
    public static String findMinNumberPattern(String str)
    {
        String ans = ""; // Minimum number following pattern
 
        int i = 0;
        int cur = 1; // cur val following pattern
        int dCount = 0; // Count of char 'D'
        while (i < str.length()) {
 
            char ch = str.charAt(i);
 
            // If 1st ch == 'I', incr and add to ans
            if (i == 0 && ch == 'I') {
                ans += cur;
                cur++;
            }
 
            // If cur char == 'D',
            // incr dCount as well, since we always
            // start counting for dCount from i+1
            if (ch == 'D') {
                dCount++;
            }
 
            int j = i + 1; // Count 'D' from i+1 index
            while (j < str.length()
                   && str.charAt(j) == 'D') {
                dCount++;
                j++;
            }
 
            int k = dCount;  // Store dCount
            while (dCount >= 0) {
                ans += (cur + dCount);
                dCount--;
            }
 
            cur += (k + 1); // Manages next cur val
            dCount = 0;
            i = j;
        }
 
        return ans;
    }
    public static void main(String[] args)
    {
        System.out.println(findMinNumberPattern("DIDID"));
        System.out.println(findMinNumberPattern("DIDIII"));
        System.out.println(findMinNumberPattern("DDDIIDI"));
        System.out.println(findMinNumberPattern("IDIDIID"));
        System.out.println(findMinNumberPattern("DIIDIDD"));
        System.out.println(findMinNumberPattern("IIDIDDD"));
    }
}
 
// This code is contributed by Arun M

Python3

# This code illustrates to find minimum number following
# pattern with optimized space and modular code.
 
# This function returns minimum number following
# pattern of increasing or decreasing sequence.
def findMinNumberPattern(Str):
 
    ans = "" # Minimum number following pattern
 
    i = 0
    cur = 1 # cur val following pattern
    dCount = 0 # Count of char 'D'
    while (i < len(Str)) :
 
        ch = Str[i]
 
        # If 1st ch == 'I', incr and add to ans
        if (i == 0 and ch == 'I') :
            ans += str(cur)
            cur+=1
 
        # If cur char == 'D',
        # incr dCount as well, since we always
        # start counting for dCount from i+1
        if (ch == 'D') :
            dCount+=1
         
 
        j = i + 1 # Count 'D' from i+1 index
        while (j < len(Str) and Str[j] == 'D') :
            dCount+=1
            j+=1
         
 
        k = dCount  # Store dCount
        while (dCount >= 0) :
            ans += str(cur + dCount)
            dCount-=1
         
 
        cur += (k + 1) # Manages next cur val
        dCount = 0
        i = j
 
    return ans
     
print(findMinNumberPattern("DIDID"))
print(findMinNumberPattern("DIDIII"))
print(findMinNumberPattern("DDDIIDI"))
print(findMinNumberPattern("IDIDIID"))
print(findMinNumberPattern("DIIDIDD"))
print(findMinNumberPattern("IIDIDDD"))
 
# This code is contributed by mukesh07.

C#

// This code illustrates to find minimum number following
// pattern with optimized space and modular code.
using System;
class GFG {
     
    // This function returns minimum number following
    // pattern of increasing or decreasing sequence.
    public static string findMinNumberPattern(string str)
    {
        string ans = ""; // Minimum number following pattern
  
        int i = 0;
        int cur = 1; // cur val following pattern
        int dCount = 0; // Count of char 'D'
        while (i < str.Length) {
  
            char ch = str[i];
  
            // If 1st ch == 'I', incr and add to ans
            if (i == 0 && ch == 'I') {
                ans += cur;
                cur++;
            }
  
            // If cur char == 'D',
            // incr dCount as well, since we always
            // start counting for dCount from i+1
            if (ch == 'D') {
                dCount++;
            }
  
            int j = i + 1; // Count 'D' from i+1 index
            while (j < str.Length
                   && str[j] == 'D') {
                dCount++;
                j++;
            }
  
            int k = dCount;  // Store dCount
            while (dCount >= 0) {
                ans += (cur + dCount);
                dCount--;
            }
  
            cur += (k + 1); // Manages next cur val
            dCount = 0;
            i = j;
        }
  
        return ans;
    }
     
  static void Main() {
    Console.WriteLine(findMinNumberPattern("DIDID"));
    Console.WriteLine(findMinNumberPattern("DIDIII"));
    Console.WriteLine(findMinNumberPattern("DDDIIDI"));
    Console.WriteLine(findMinNumberPattern("IDIDIID"));
    Console.WriteLine(findMinNumberPattern("DIIDIDD"));
    Console.WriteLine(findMinNumberPattern("IIDIDDD"));
  }
}
 
// This code is contributed by mukesh07.

Javascript


输出 :

214365
2143567
43215768
13254687
21354876
12438765

时间复杂度:O(n)

空间复杂度:O(1)