📌  相关文章
📜  检查一个字符串可以通过对子字符串进行排序来转换为另一个字符串

📅  最后修改于: 2021-09-07 04:08:08             🧑  作者: Mango

给定两个字符串str1str2,每个字符串的长度为N并且仅由小写英文字母组成,任务是通过执行以下操作任意次数来检查字符串str1 是否可以转换为字符串str2

  • str1 中选择一个非空子串并按字典顺序就地排序,以非递减顺序排列子串的字符。

例子 :

处理方法:按照以下步骤解决问题:

  • 观察到,在字符串str1 中,如果有两个字符str1[i]str2[j]使得str1[i] < str1[j] ,则可以交换这些字符。
  • 换句话说,可以将一个字符自由地向左移动,直到遇到一个较小的字符。例如,“acdb”可以转换为“ acbd ”、“ abcd ”,因为“ b ”可以自由地向左移动,直到出现“ a ”。
  • 因此,检查是否可以将所需的字符向左移动到它们在字符串str2中的相应位置。
  • 将字符串str1的每个字符的索引存储在一个数组中。
  • 遍历字符串str2,对于每个字符,检查str1 中的相同字符是否可以移动到该位置。

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to check if str1 can be
// transformed to t by sorting substrings
void canTransform(string& s, string& t)
{
    int n = s.length();
 
    // Occur[i] stores the indices
    // of char ('a'+i) in string s
    vector occur[26];
    for (int x = 0; x < n; x++) {
        char ch = s[x] - 'a';
        occur[ch].push_back(x);
    }
 
    // idx[i] stores the next available
    // index of char ('a'+i) in occur[i]
    vector idx(26, 0);
    bool poss = true;
    for (int x = 0; x < n; x++) {
        char ch = t[x] - 'a';
 
        // If this char is not available
        // anymore
        if (idx[ch] >= occur[ch].size()) {
 
            // Conversion not possible
            poss = false;
            break;
        }
        for (int small = 0; small < ch; small++) {
 
            // If one of the smaller characters
            // is available and occurs before
            if (idx[small] < occur[small].size()
                && occur[small][idx[small]]
                       < occur[ch][idx[ch]]) {
 
                // Conversion not possible
                poss = false;
                break;
            }
        }
        idx[ch]++;
    }
 
    // Print the answer
    if (poss) {
        cout << "Yes" << endl;
    }
    else {
        cout << "No" << endl;
    }
}
 
// Driver Code
int main()
{
    string s, t;
 
    s = "hdecb";
    t = "cdheb";
 
    canTransform(s, t);
    return 0;
}


Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to check if str1
// can be transformed to t by
// sorting subStrings
static void canTransform(String s,
                         String t)
{
  int n = s.length();
 
  // Occur[i] stores the indices
  // of char ('a'+i) in String s
  Vector occur[] = new Vector[26];
   
  for (int i = 0; i < occur.length; i++)
    occur[i] = new Vector();
   
  for (int x = 0; x < n; x++)
  {
    char ch = (char)(s.charAt(x) - 'a');
    occur[ch].add(x);
  }
 
  // idx[i] stores the next available
  // index of char ('a'+i) in occur[i]
  int []idx = new int[26];
  boolean poss = true;
   
  for (int x = 0; x < n; x++)
  {
    char ch = (char)(t.charAt(x) - 'a');
 
    // If this char is
    // not available anymore
    if (idx[ch] >= occur[ch].size())
    {
      // Conversion not possible
      poss = false;
      break;
    }
    for (int small = 0; small < ch; small++)
    {
      // If one of the smaller characters
      // is available and occurs before
      if (idx[small] < occur[small].size() &&
          occur[small].get(idx[small]) <
          occur[ch].get(idx[ch]))
      {
        // Conversion not possible
        poss = false;
        break;
      }
    }
    idx[ch]++;
  }
 
  // Print the answer
  if (poss)
  {
    System.out.print("Yes" + "\n");
  }
  else
  {
    System.out.print("No" + "\n");
  }
}
 
// Driver Code
public static void main(String[] args)
{
  String s, t;
  s = "hdecb";
  t = "cdheb";
  canTransform(s, t);
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program to implement
# the above approach
 
# Function to check if str1 can be
# transformed to t by sorting substrings
def canTransform(s, t):
     
    n = len(s)
 
    # Occur[i] stores the indices
    # of ('a'+i) in string s
    occur = [[] for i in range(26)]
     
    for x in range(n):
        ch = ord(s[x]) - ord('a')
        occur[ch].append(x)
 
    # idx[i] stores the next available
    # index of ('a'+i) in occur[i]
    idx = [0] * (26)
    poss = True
     
    for x in range(n):
        ch = ord(t[x]) - ord('a')
 
        # If this is not available
        # anymore
        if (idx[ch] >= len(occur[ch])):
 
            # Conversion not possible
            poss = False
            break
 
        for small in range(ch):
 
            # If one of the smaller characters
            # is available and occurs before
            if (idx[small] < len(occur[small]) and
                occur[small][idx[small]] <
                occur[ch][idx[ch]]):
 
                # Conversion not possible
                poss = False
                break
             
        idx[ch] += 1
 
    # Print the answer
    if (poss):
        print("Yes")
    else:
        print("No")
 
# Driver Code
if __name__ == '__main__':
 
    s = "hdecb"
    t = "cdheb"
 
    canTransform(s, t)
 
# This code is contributed by mohit kumar 29


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to check if str1
// can be transformed to t by
// sorting subStrings
static void canTransform(String s,
                         String t)
{
  int n = s.Length;
 
  // Occur[i] stores the indices
  // of char ('a'+i) in String s
  List []occur = new List[26];
   
  for(int i = 0; i < occur.Length; i++)
    occur[i] = new List();
   
  for(int x = 0; x < n; x++)
  {
    char ch = (char)(s[x] - 'a');
    occur[ch].Add(x);
  }
 
  // idx[i] stores the next available
  // index of char ('a'+i) in occur[i]
  int []idx = new int[26];
  bool poss = true;
   
  for(int x = 0; x < n; x++)
  {
    char ch = (char)(t[x] - 'a');
 
    // If this char is
    // not available anymore
    if (idx[ch] >= occur[ch].Count)
    {
         
      // Conversion not possible
      poss = false;
      break;
    }
    for(int small = 0; small < ch; small++)
    {
         
      // If one of the smaller characters
      // is available and occurs before
      if (idx[small] < occur[small].Count &&
            occur[small][idx[small]] <
            occur[ch][idx[ch]])
      {
           
        // Conversion not possible
        poss = false;
        break;
      }
    }
    idx[ch]++;
  }
 
  // Print the answer
  if (poss)
  {
    Console.Write("Yes" + "\n");
  }
  else
  {
    Console.Write("No" + "\n");
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  String s, t;
  s = "hdecb";
  t = "cdheb";
   
  canTransform(s, t);
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
Yes

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live