📌  相关文章
📜  生成具有给定操作的序列

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

生成具有给定操作的序列

给定一个字符串S  其中仅包含I  (增加)和D  (减少)。任务是返回整数[0, 1, ..., N]的任何排列,其中N ≤ S 的长度,使得对于所有i = 0, ..., N-1

  1. 如果 S[i] == “D”,则 A[i] > A[i+1]
  2. 如果 S[i] == “I”,则 A[i] < A[i+1]。

请注意,输出必须包含不同的元素。
例子:

方法:如果S[0] == “I” ,则选择0  作为第一个元素。同样,如果S[0] == “D” ,则选择N  作为第一个元素。现在对于每个I  操作,从范围[0, N]中选择下一个之前没有选择过的最大元素,对于D  操作,选择下一个最小值。
下面是上述方法的实现:

C++
//C++ Implementation of above approach
#include
using namespace std;
    // function to find minimum required permutation
    void  StringMatch(string s)
    {
    int lo=0, hi = s.length(), len=s.length();
    vector ans;
    for (int x=0;x


Java
// Java Implementation of above approach
import java.util.*;
 
class GFG
{
 
// function to find minimum required permutation
static void StringMatch(String s)
{
    int lo=0, hi = s.length(), len=s.length();
    Vector ans = new Vector<>();
    for (int x = 0; x < len; x++)
    {
        if (s.charAt(x) == 'I')
        {
            ans.add(lo) ;
            lo += 1;
        }
        else
        {
            ans.add(hi) ;
            hi -= 1;
        }
    }
            ans.add(lo) ;
    System.out.print("[");
    for(int i = 0; i < ans.size(); i++)
    {
        System.out.print(ans.get(i));
        if(i != ans.size()-1)
            System.out.print(",");
    }
    System.out.print("]");
}
 
// Driver code
public static void main(String[] args)
{
    String S = "IDID";
    StringMatch(S);
}
}
 
// This code is contributed by Rajput-Ji


Python
# Python Implementation of above approach
 
# function to find minimum required permutation
def StringMatch(S):
    lo, hi = 0, len(S)
    ans = []
    for x in S:
        if x == 'I':
            ans.append(lo)
            lo += 1
        else:
            ans.append(hi)
            hi -= 1
 
    return ans + [lo]
 
# Driver code
S = "IDID"
print(StringMatch(S))


C#
// C# Implementation of above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
// function to find minimum required permutation
static void StringMatch(String s)
{
    int lo=0, hi = s.Length, len=s.Length;
    List ans = new List();
    for (int x = 0; x < len; x++)
    {
        if (s[x] == 'I')
        {
            ans.Add(lo) ;
            lo += 1;
        }
        else
        {
            ans.Add(hi) ;
            hi -= 1;
        }
    }
            ans.Add(lo) ;
    Console.Write("[");
    for(int i = 0; i < ans.Count; i++)
    {
        Console.Write(ans[i]);
        if(i != ans.Count-1)
            Console.Write(",");
    }
    Console.Write("]");
}
 
// Driver code
public static void Main(String[] args)
{
    String S = "IDID";
    StringMatch(S);
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
[0, 4, 1, 3, 2]