生成具有给定操作的序列
给定一个字符串其中仅包含 (增加)和 (减少)。任务是返回整数[0, 1, ..., N]的任何排列,其中N ≤ S 的长度,使得对于所有i = 0, ..., N-1 :
- 如果 S[i] == “D”,则 A[i] > A[i+1]
- 如果 S[i] == “I”,则 A[i] < A[i+1]。
请注意,输出必须包含不同的元素。
例子:
Input: S = “DDI”
Output: [3, 2, 0, 1]
Input: S = “IDID”
Output: [0, 4, 1, 3, 2]
方法:如果S[0] == “I” ,则选择作为第一个元素。同样,如果S[0] == “D” ,则选择作为第一个元素。现在对于每个操作,从范围[0, N]中选择下一个之前没有选择过的最大元素,对于操作,选择下一个最小值。
下面是上述方法的实现:
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]