Advertisement
a53

MinLexSwap

a53
Jun 23rd, 2021
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. string MinLexSwap(string s)
  2. {
  3. int len = s.size();
  4. int loccur[26];
  5. memset(loccur, -1, sizeof(loccur));
  6. for(int i = len - 1; i >= 0; --i)
  7. {
  8. int chI = s[i] - 'a';
  9. if(loccur[chI] == -1)
  10. loccur[chI] = i;
  11. }
  12. string sorted_s = s;
  13. sort(sorted_s.begin(), sorted_s.end());
  14. if(sorted_s==s)
  15. {
  16. int i=len-1;
  17. while(s[i]==s[i-1] && i>0)
  18. i--;
  19. if(i>0)
  20. swap(s[i],s[i-1]);
  21.  
  22. }
  23. else
  24. {
  25. for(int i = 0; i < len; ++i)
  26. {
  27. if(s[i]!= sorted_s[i])
  28. {
  29. int chI = sorted_s[i] - 'a';
  30. int last_occ = loccur[chI];
  31. swap(s[i], s[last_occ]);
  32. break;
  33. }
  34. }
  35. }
  36. return s;
  37. }
  38.  
  39. /**
  40. so
  41. string MinLexSwap(string s)
  42. {
  43. int i, j, n;
  44. string t;
  45. n = s.length();
  46. t = s;
  47. sort(t.begin(), t.end());
  48. if (s == t) /// s este ordonat crescator
  49. {
  50. j = i = n - 1;
  51. while (s[j] == s[i])
  52. j--;
  53. swap(s[j + 1], s[j]);
  54. return s;
  55. }
  56. for (i = 0; s[i] == t[i]; i++)
  57. ;
  58. for (j = n - 1; s[j] != t[i]; j--)
  59. ;
  60. swap(s[i], s[j]);
  61. return s;
  62. }
  63. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement