fork download
  1. #include<iostream>
  2. #include<cstdio>
  3. #include<vector>
  4. #include<bits/stdc++.h>
  5. using namespace std;
  6. int Length(string s)
  7. {
  8. int len=0;
  9. for(int i=0;s[i]!='\0';i++)
  10. {
  11. len++;
  12. }
  13. return len;
  14. }
  15. vector <int> SubStringFind(string s, string sub)
  16. {
  17. int lens = Length(s);
  18. int lensub = Length(sub);
  19. vector <int> pos;
  20. int paisi = 0;
  21. for(int i=0;i<=lens-lensub;i++)
  22. {
  23. int matched = 0;
  24. for(int j=0;j<lensub;j++)
  25. {
  26. if(sub[j] == s[i+j])
  27. {
  28. matched++;
  29. continue;
  30. }
  31. else
  32. break;
  33. }
  34. if(matched == lensub)
  35. {
  36. pos.push_back(i);
  37. }
  38. }
  39. return pos;
  40. }
  41.  
  42. string Delete(string s, string sub)
  43. {
  44. int lens = Length(s);
  45. int lensub = Length(sub);
  46. vector <int> pos;
  47. pos = SubStringFind(s,sub);
  48. string res = "";
  49. int kototomo = 0;
  50. for(int i=0;i<lens;i++)
  51. {
  52. if(kototomo > pos.size() || i != pos[kototomo])
  53. {
  54. res = res + s[i];
  55. }
  56. else
  57. {
  58. i+= (lensub-1);
  59. kototomo++;
  60. }
  61. }
  62. return res;
  63. }
  64. string InsertAtPos(string s, int pos, string sub)
  65. {
  66. string res = "";
  67. int lens = Length(s);
  68. int lensub = Length(sub);
  69. for(int i=0;i<pos;i++)
  70. {
  71. res = res + s[i];
  72. }
  73. res = res + sub;
  74. for(int i=pos;i<lens;i++)
  75. {
  76. res = res + s[i];
  77. }
  78. return res;
  79. }
  80.  
  81. string Replace(string s, string sub1, string sub2)
  82. {
  83. int lens = Length(s);
  84. int lensub1 = Length(sub1);
  85. int lensub2 = Length(sub2);
  86.  
  87. vector <int> pos;
  88. pos = SubStringFind(s,sub1);
  89. string res;
  90. res = Delete(s,sub1);
  91. for(int i=0;i<pos.size();i++)
  92. {
  93. res = InsertAtPos(res,pos[i]+(i*(lensub2-lensub1)),sub2);
  94. }
  95. return res;
  96. }
  97.  
  98. int main()
  99. {
  100. //memset(kothay,100,-1);
  101. vector <int> kothay;
  102. string s,sub1,sub2;
  103. int pos;
  104. cin>>s>>sub1>>sub2;
  105. string res = Replace(s,sub1,sub2);
  106. cout<<res;
  107. return 0;
  108. }
Success #stdin #stdout 0s 5308KB
stdin
abcdcbcd
bcd
pqrst
stdout
apqrstcpqrst