fork download
  1. //
  2. // main.cpp
  3. // Custom Sort
  4. //
  5. // Created by Himanshu on 16/08/21.
  6. //
  7.  
  8. #include <iostream>
  9. #include <string>
  10. using namespace std;
  11.  
  12. //String S is order & string T is the given string
  13. string customSortString(string S, string T) {
  14. string ans = "";
  15. for (int i=0; i<S.size(); i++) {
  16. for (int j=0; j<T.size(); j++) {
  17. if (T[j] == S[i]) {
  18. ans.push_back(S[i]);
  19. //marking j character as selected
  20. T[j] = 'A';
  21. }
  22. }
  23. }
  24. for (int i=0; i<T.size(); i++) {
  25. if (T[i] != 'A') {
  26. //Adding remaining (not selected before) characters to the answer
  27. ans.push_back(T[i]);
  28. }
  29. }
  30. return ans;
  31. }
  32.  
  33. int main() {
  34. // your code goes here
  35. cout<<customSortString("cba", "abcd")<<endl;
  36. cout<<customSortString("cbafg", "abcd")<<endl;
  37. cout<<customSortString("cba", "dbca")<<endl;
  38. cout<<customSortString("cbahkj", "hkabc")<<endl;
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0s 5556KB
stdin
Standard input is empty
stdout
cbad
cbad
cbad
cbahk