📜  将给定的数字字符串分成最多两个递增的子序列,这些子序列在连接时形成一个递增的字符串

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

将给定的数字字符串分成最多两个递增的子序列,这些子序列在连接时形成一个递增的字符串

给定一个由N个数字组成的字符串S ,任务是将字符串分成最多两个递增的子序列,这样它们的连接也形成一个递增的字符串。如果无法这样做,则打印“-1”

例子:

朴素方法:解决问题的最简单方法是生成所有可能的子序列并检查任何两个不重叠的子序列是否满足给定条件。如果发现是true ,则打印两个子序列。

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

有效方法:上述方法可以通过将所有小于X的值放在第一个子序列中,将所有大于X的元素放在第二个子序列中,并且所有等于X的元素都根据它们在所有X中的位置来决定在[0, 9]范围内。请按照以下步骤解决问题:

  • 初始化一个变量,比如pos来存储小于pos在第一个子序列中的位置,大于pos在第二个子序列中的位置,并且等于pos的元素将根据它们的位置在子序列上。
  • 初始化一个数组res[] ,它将存储哪个元素属于哪个子序列。
  • [0, 9]范围内迭代pos并执行以下步骤:
    1. 将两个变量last1初始化为0将 last2初始化为pos ,分别存储已放入子序列 1 和 2 中的最后一个元素。
    2. 将一个布尔变量标志初始化为1 ,用于存储处理后的子序列是否有效。
    3. 使用i作为变量在[0, N-1]范围内迭代并执行以下步骤:
      • 如果last2 ≤ S[i] ,则修改last2的值为S[i]res[i]2
      • 否则,如果last1 ≤ S[i] ,则将last1的值修改为S[i]并将res[i]的值修改为1
      • 否则,将标志的值修改为0
    4. 检查last的值是否大于pos ,然后将flag的值修改为0
    5. 如果flag的值为1 ,则打印数组res作为答案并跳出循环。
  • 完成上述步骤后,如果没有找到可能的子序列,则打印-1

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to check for valid subsequences
void findSubsequence(string str)
{
    int n = str.size();
 
    // Stores which element belongs to
    // which subsequence
    char res[n];
    for (int i = 0; i < n; i++)
        res[i] = 0;
 
    // Check for each pos if a possible
    // subsequence exist or not
    for (int pos = 0; pos <= 9; pos++) {
 
        // Last member of 1 subsequence
        char lst1 = '0';
        bool flag = 1;
 
        // Last Member of 2nd subsequence
        char lst2 = pos + '0';
        for (int i = 0; i < n; i++) {
 
            // Check if current element can
            // go to 2nd subsequence
            if (lst2 <= str[i]) {
                res[i] = '2';
                lst2 = str[i];
            }
 
            // Check if the current elements
            // belongs to first subsequence
            else if (lst1 <= str[i]) {
                res[i] = '1';
                lst1 = str[i];
            }
 
            // If the current element does
            // not belong to any subsequence
            else
                flag = 0;
        }
 
        // Check if last digit of first
        // subsequence is greater than pos
        if (lst1 > pos + '0')
            flag = 0;
 
        // If a subsequence is found,
        // find the subsequences
        if (flag) {
 
            // Stores the resulting
            // subsequences
            string S1 = "";
            string S2 = "";
 
            for (int i = 0; i < n; i++) {
 
                if (res[i] == '1') {
                    S1 += str[i];
                }
                else {
                    S2 += str[i];
                }
            }
 
            // Print the subsequence
            cout << S1 << ' ' << S2 << endl;
            return;
        }
    }
 
    // If no subsequence found, print -1
    cout << "-1";
}
 
// Driver Code
int main()
{
    string S = "040425524644";
    findSubsequence(S);
 
    S = "123456789";
    findSubsequence(S);
 
    return 0;
}


Java
// Java program for the above approach
class GFG{
 
// Function to check for valid subsequences
static void findSubsequence(String str)
{
    int n = str.length();
 
    // Stores which element belongs to
    // which subsequence
    char []res = new char[n];
    for (int i = 0; i < n; i++)
        res[i] = 0;
 
    // Check for each pos if a possible
    // subsequence exist or not
    for (int pos = 0; pos <= 9; pos++) {
 
        // Last member of 1 subsequence
        char lst1 = '0';
        boolean flag = true;
 
        // Last Member of 2nd subsequence
        char lst2 = (char) (pos + '0');
        for (int i = 0; i < n; i++) {
 
            // Check if current element can
            // go to 2nd subsequence
            if (lst2 <= str.charAt(i)) {
                res[i] = '2';
                lst2 = str.charAt(i);
            }
 
            // Check if the current elements
            // belongs to first subsequence
            else if (lst1 <= str.charAt(i)) {
                res[i] = '1';
                lst1 = str.charAt(i);
            }
 
            // If the current element does
            // not belong to any subsequence
            else
                flag = false;
        }
 
        // Check if last digit of first
        // subsequence is greater than pos
        if (lst1 > pos + '0')
            flag = false;
 
        // If a subsequence is found,
        // find the subsequences
        if (flag) {
 
            // Stores the resulting
            // subsequences
            String S1 = "";
            String S2 = "";
 
            for (int i = 0; i < n; i++) {
 
                if (res[i] == '1') {
                    S1 += str.charAt(i);
                }
                else {
                    S2 += str.charAt(i);
                }
            }
 
            // Print the subsequence
            System.out.print(S1 + " " + S2 +"\n");
            return;
        }
    }
 
    // If no subsequence found, print -1
    System.out.print("-1");
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "040425524644";
    findSubsequence(S);
 
    S = "123456789";
    findSubsequence(S);
 
}
}
 
// This code is contributed by 29AjayKumar.


Python3
# Python 3 program for the above approach
 
# Function to check for valid subsequences
def findSubsequence(str):
    n = len(str)
 
    # Stores which element belongs to
    # which subsequence
    res = ['0' for i in range(n)]
     
    # Check for each pos if a possible
    # subsequence exist or not
    for pos in range(10):
       
        # Last member of 1 subsequence
        lst1 = '0'
        flag = 1
 
        # Last Member of 2nd subsequence
        lst2 = chr(pos + 48)
        for i in range(n):
           
            # Check if current element can
            # go to 2nd subsequence
            if (lst2 <= str[i]):
                res[i] = '2'
                lst2 = str[i]
 
            # Check if the current elements
            # belongs to first subsequence
            elif(lst1 <= str[i]):
                res[i] = '1'
                lst1 = str[i]
 
            # If the current element does
            # not belong to any subsequence
            else:
                flag = 0
 
        # Check if last digit of first
        # subsequence is greater than pos
        if (lst1 >  chr(pos + 48)):
            flag = 0
 
        # If a subsequence is found,
        # find the subsequences
        if (flag):
           
            # Stores the resulting
            # subsequences
            S1 = ""
            S2 = ""
 
            for i in range(n):
                if (res[i] == '1'):
                    S1 += str[i]
                else:
                    S2 += str[i]
 
            # Print the subsequence
            print(S1,S2)
            return
     
    # If no subsequence found, print -1
    print("-1")
 
# Driver Code
if __name__ == '__main__':
    S = "040425524644"
    findSubsequence(S)
 
    S = "123456789"
    findSubsequence(S)
     
    # This code is contributed by SURENDRA_GANGWAR.


C#
// C# program for the approach
using System;
using System.Collections.Generic;
 
class GFG {
 
// Function to check for valid subsequences
static void findSubsequence(string str)
{
    int n = str.Length;
  
    // Stores which element belongs to
    // which subsequence
    char[] res = new char[n];
    for (int i = 0; i < n; i++)
        res[i] = '0';
  
    // Check for each pos if a possible
    // subsequence exist or not
    for (int pos = 0; pos <= 9; pos++) {
  
        // Last member of 1 subsequence
        char lst1 = '0';
        bool flag = true;
  
        // Last Member of 2nd subsequence
        char lst2 = (char) (pos + '0');
        for (int i = 0; i < n; i++) {
  
            // Check if current element can
            // go to 2nd subsequence
            if (lst2 <= str[i]) {
                res[i] = '2';
                lst2 = str[i];
            }
  
            // Check if the current elements
            // belongs to first subsequence
            else if (lst1 <= str[i]) {
                res[i] = '1';
                lst1 = str[i];
            }
  
            // If the current element does
            // not belong to any subsequence
            else
                flag = false;
        }
  
        // Check if last digit of first
        // subsequence is greater than pos
        if (lst1 > pos + '0')
            flag = false;
  
        // If a subsequence is found,
        // find the subsequences
        if (flag) {
  
            // Stores the resulting
            // subsequences
            string S1 = "";
            string S2 = "";
  
            for (int i = 0; i < n; i++) {
  
                if (res[i] == '1') {
                    S1 += str[i];
                }
                else {
                    S2 += str[i];
                }
            }
  
            // Print the subsequence
            Console.WriteLine(S1 + ' ' + S2);
            return;
        }
    }
  
    // If no subsequence found, print -1
    Console.Write("-1");
}
  
    // Driver Code
    public static void Main()
    {
        string S = "040425524644";
        findSubsequence(S);
  
        S = "123456789";
        findSubsequence(S);
    }
}
 
// This code is contributed by sanjoy_62.


Javascript


输出:
0022444 44556 
123456789

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