logo

قم بفرز سلسلة وفقًا للترتيب المحدد بواسطة سلسلة أخرى

إعطاء سلسلتين (من الأحرف الصغيرة) نمطًا وسلسلة. وتتمثل المهمة في فرز السلاسل وفقًا للترتيب الذي يحدده النمط. يمكن الافتراض أن النموذج يحتوي على جميع أحرف السلسلة وأن جميع الأحرف في النموذج تظهر مرة واحدة فقط.

أمثلة:  

Input : pat = 'bca' str = 'abc' Output : str = 'bca' Input : pat = 'bxyzca' str = 'abcabcabc' Output : str = 'bbbcccaaa' Input : pat = 'wcyuogmlrdfphitxjakqvzbnes' str = 'jcdokai' Output : str = 'codijak'

النهج 1: تتمثل الفكرة في حساب تكرارات جميع الأحرف في str أولاً وتخزين هذه الأعداد في مصفوفة العد. ثم قم باجتياز النمط من اليسار إلى اليمين ولكل حرف pat[i] راجع عدد المرات التي يظهر فيها في مصفوفة العد وانسخ هذا الحرف عدة مرات إلى str.
وفيما يلي تنفيذ الفكرة المذكورة أعلاه. 



تطبيق:

C++
// C++ program to sort a string according to the // order defined by a pattern string #include    using namespace std; const int MAX_CHAR = 26; // Sort str according to the order defined by pattern. void sortByPattern(string& str string pat) {  // Create a count array store count of characters in str.  int count[MAX_CHAR] = { 0 };  // Count number of occurrences of each character  // in str.  for (int i = 0; i < str.length(); i++)  count[str[i] - 'a']++;  // Traverse the pattern and print every characters  // same number of times as it appears in str. This  // loop takes O(m + n) time where m is length of  // pattern and n is length of str.  int index = 0;  for (int i = 0; i < pat.length(); i++)  for (int j = 0; j < count[pat[i] - 'a']; j++)  str[index++] = pat[i]; } // Driver code int main() {  string pat = 'bca';  string str = 'abc';  sortByPattern(str pat);  cout << str;  return 0; } 
Java
// Java program to sort a string according to the // order defined by a pattern string class GFG {  static int MAX_CHAR = 26;  // Sort str according to the order defined by pattern.  static void sortByPattern(char[] str char[] pat)  {  // Create a count array store  // count of characters in str.  int count[] = new int[MAX_CHAR];  // Count number of occurrences of  // each character in str.  for (int i = 0; i < str.length; i++) {  count[str[i] - 'a']++;  }  // Traverse the pattern and print every characters  // same number of times as it appears in str. This  // loop takes O(m + n) time where m is length of  // pattern and n is length of str.  int index = 0;  for (int i = 0; i < pat.length; i++) {  for (int j = 0; j < count[pat[i] - 'a']; j++) {  str[index++] = pat[i];  }  }  }  // Driver code  public static void main(String args[])  {  char[] pat = 'bca'.toCharArray();  char[] str = 'abc'.toCharArray();  sortByPattern(str pat);  System.out.println(String.valueOf(str));  } } // This code has been contributed by 29AjayKumar 
Python3
# Python3 program to sort a string according to  # the order defined by a pattern string MAX_CHAR = 26 # Sort str according to the order defined by pattern. def sortByPattern(str pat): global MAX_CHAR # Create a count array store count # of characters in str. count = [0] * MAX_CHAR # Count number of occurrences of  # each character in str. for i in range (0 len(str)): count[ord(str[i]) - 97] += 1 # Traverse the pattern and print every characters # same number of times as it appears in str. This # loop takes O(m + n) time where m is length of # pattern and n is length of str. index = 0; str = '' for i in range (0 len(pat)): j = 0 while(j < count[ord(pat[i]) - ord('a')]): str += pat[i] j = j + 1 index += 1 return str # Driver code pat = 'bca' str = 'abc' print(sortByPattern(str pat)) # This code is contributed by ihritik 
C#
// C# program to sort a string according to the // order defined by a pattern string using System; class GFG {  static int MAX_CHAR = 26;  // Sort str according to the order defined by pattern.  static void sortByPattern(char[] str char[] pat)  {  // Create a count array store  // count of characters in str.  int[] count = new int[MAX_CHAR];  // Count number of occurrences of  // each character in str.  for (int i = 0; i < str.Length; i++) {  count[str[i] - 'a']++;  }  // Traverse the pattern and print every characters  // same number of times as it appears in str. This  // loop takes O(m + n) time where m is length of  // pattern and n is length of str.  int index = 0;  for (int i = 0; i < pat.Length; i++) {  for (int j = 0; j < count[pat[i] - 'a']; j++) {  str[index++] = pat[i];  }  }  }  // Driver code  public static void Main(String[] args)  {  char[] pat = 'bca'.ToCharArray();  char[] str = 'abc'.ToCharArray();  sortByPattern(str pat);  Console.WriteLine(String.Join('' str));  } } /* This code contributed by PrinciRaj1992 */ 
JavaScript
<script> // Javascript program to sort a string according to the // order defined by a pattern string let MAX_CHAR = 26; // Sort str according to the order defined by pattern. function sortByPattern(strpat) {  // Create a count array stor  // count of characters in str.  let count = new Array(MAX_CHAR);  for(let i = 0; i < MAX_CHAR; i++)  {  count[i] = 0;  }    // Count number of occurrences of  // each character in str.  for (let i = 0; i < str.length; i++) {  count[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;  }    // Traverse the pattern and print every characters  // same number of times as it appears in str. This  // loop takes O(m + n) time where m is length of  // pattern and n is length of str.  let index = 0;  for (let i = 0; i < pat.length; i++) {  for (let j = 0; j < count[pat[i].charCodeAt(0) - 'a'.charCodeAt(0)]; j++) {  str[index++] = pat[i];  }  } } // Driver code let pat = 'bca'.split(''); let str = 'abc'.split(''); sortByPattern(str pat); document.write((str).join('')); // This code is contributed by rag2127 </script> 

الإخراج
bca

تعقيد الوقت: يا (م + ن) حيث m هو طول النموذج و n هو طول str.
المساحة الإضافية:  O(1)  

النهج 2: 

يمكننا تمرير مُقارن إلى الدالةsort() وفرز السلسلة وفقًا للنمط.

C++
#include    using namespace std; // Declaring a vector globally that stores which character // is occurring first vector<int> position(26 -1); //Comparator function bool cmp(char& char1 char& char2) {  return position[char1 - 'a'] < position[char2 - 'a']; } int main() {  // Pattern  string pat = 'wcyuogmlrdfphitxjakqvzbnes';  for (int i = 0; i < pat.length(); i++) {  if (position[pat[i] - 'a'] == -1)  position[pat[i] - 'a'] = i;  }  // String to be sorted  string str = 'jcdokai';  // Passing a comparator to sort function  sort(str.begin() str.end() cmp);  cout << str; } 
Java
import java.util.*; class Main {  // Declaring a list globally that stores which character is occurring first  static List<Integer> position = new ArrayList<>(Collections.nCopies(26 -1));  // Comparator function  static int cmp(char char1 char char2) {  if (position.get(char1 - 'a') < position.get(char2 - 'a')) {  return -1;  } else if (position.get(char1 - 'a') > position.get(char2 - 'a')) {  return 1;  } else {  return 0;  }  }  public static void main(String[] args) {  // Pattern  String pat = 'wcyuogmlrdfphitxjakqvzbnes';  for (int i = 0; i < pat.length(); i++) {  if (position.get(pat.charAt(i) - 'a') == -1) {  position.set(pat.charAt(i) - 'a' i);  }  }  // String to be sorted  String str = 'jcdokai';  // Passing a comparator to the sorted function  char[] charArr = str.toCharArray();  Arrays.sort(charArr new Comparator<Character>() {  public int compare(Character c1 Character c2) {  return cmp(c1 c2);  }  });  String sortedStr = new String(charArr);  System.out.println(sortedStr);  } } 
Python3
from typing import List from functools import cmp_to_key # Declaring a list globally that stores which character is occurring first position: List[int] = [-1] * 26 # Comparator function def cmp(char1: str char2: str) -> int: if position[ord(char1) - ord('a')] < position[ord(char2) - ord('a')]: return -1 elif position[ord(char1) - ord('a')] > position[ord(char2) - ord('a')]: return 1 else: return 0 if __name__ == '__main__': # Pattern pat = 'wcyuogmlrdfphitxjakqvzbnes' for i in range(len(pat)): if position[ord(pat[i]) - ord('a')] == -1: position[ord(pat[i]) - ord('a')] = i # String to be sorted str = 'jcdokai' # Passing a comparator to the sorted function sorted_str = sorted(str key=cmp_to_key(cmp)) print(''.join(sorted_str)) # This code is contributed by adityashatmfh 
JavaScript
<script> // Declaring a vector globally that stores which character // is occurring first let position = new Array(26).fill(-1); //Comparator function function cmp(char1 char2) {  return position[char1.charCodeAt(0) - 'a'.charCodeAt(0)] - position[char2.charCodeAt(0) - 'a'.charCodeAt(0)]; } // driver code // Pattern let pat = 'wcyuogmlrdfphitxjakqvzbnes'; for (let i = 0; i <br pat.length; i++) {  if (position[pat.charCodeAt(i) - 'a'.charCodeAt(0)] == -1)  position[pat.charCodeAt(i) - 'a'.charCodeAt(0)] = i; } // String to be sorted let str = 'jcdokai'; // Passing a comparator to sort function str = str.split('').sort(cmp).join(''); document.write(str'
'
); // This code is contributed by Shinjan Patra </script>
C#
// C# program for the above approach using System; using System.Collections.Generic; using System.Linq; class GFG {  // Declaring a list globally that stores which character is occurring first  static List<int> position = Enumerable.Repeat(-1 26).ToList();  // Comparator function  static int Cmp(char char1 char char2) {  if (position[char1 - 'a'] < position[char2 - 'a']) {  return -1;  } else if (position[char1 - 'a'] > position[char2 - 'a']) {  return 1;  } else {  return 0;  }  }  public static void Main() {  // Pattern  string pat = 'wcyuogmlrdfphitxjakqvzbnes';  for (int i = 0; i < pat.Length; i++) {  if (position[pat[i] - 'a'] == -1) {  position[pat[i] - 'a'] = i;  }  }  // String to be sorted  string str = 'jcdokai';  // Passing a comparator to the sorted function  char[] charArr = str.ToCharArray();  Array.Sort(charArr new Comparison<char>(Cmp));  string sortedStr = new string(charArr);  Console.WriteLine(sortedStr);  } } // This code is contributed by sdeadityasharma 

الإخراج
codijak


تعقيد الوقت: يا (م + نلوجن ) حيث m هو طول النموذج و n هو طول str.
 المساحة الإضافية:  O(1)

يمارس : في الحل أعلاه من المفترض أن النمط يحتوي على جميع أحرف str. فكر في نسخة معدلة حيث قد لا يحتوي النمط على جميع الأحرف وتكون المهمة هي وضع جميع الأحرف المتبقية (في السلسلة ولكن ليس في النمط) في النهاية. يجب وضع الأحرف المتبقية بترتيب أبجدي. تلميح: في الحلقة الثانية عند زيادة الفهرس ووضع الحرف في str، يمكننا أيضًا تقليل العدد في ذلك الوقت. وأخيرًا، نجتاز مصفوفة العد لوضع الأحرف المتبقية بترتيب أبجدي.

 

إنشاء اختبار