Advertisement
Spocoman

03. Replace Repeating Chars

Nov 21st, 2023
1,003
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. int main() {
  7.     string str;
  8.     getline(cin, str);
  9.  
  10.     int startIndex = 0, replacedLength = 0;
  11.  
  12.     for (size_t i = 1; i <= str.length(); i++) {
  13.         if (str[startIndex] != str[i]) {
  14.             startIndex++;
  15.             replacedLength = i - startIndex;
  16.             str.replace(startIndex, replacedLength, "");
  17.             i = startIndex;
  18.         }
  19.     }
  20.        
  21.     cout << str << endl;
  22.     return 0;
  23. }
  24.  
  25. ИЛИ:
  26.  
  27. #include <iostream>
  28. #include <string>
  29.  
  30. using namespace std;
  31.  
  32. int main() {
  33.     string str;
  34.     getline(cin, str);
  35.  
  36.     int startIndex = 0, replacedLength = 0;
  37.  
  38.     for (size_t i = 1; i <= str.length(); i++) {
  39.         if (str[startIndex] != str[i]) {
  40.             startIndex++;
  41.             replacedLength = i - startIndex;
  42.             str.erase(startIndex, replacedLength);
  43.             i = startIndex;
  44.         }
  45.     }
  46.        
  47.     cout << str << endl;
  48.     return 0;
  49. }
  50.  
  51. ИЛИ:
  52.  
  53. #include <iostream>
  54. #include <string>
  55.  
  56. using namespace std;
  57.  
  58. int main() {
  59.     string str, result;
  60.     getline(cin, str);
  61.  
  62.     result = str[0];
  63.  
  64.     for (size_t i = 1; i < str.length(); i++) {
  65.         if (result[result.length() - 1] != str[i]) {
  66.             result += str[i];
  67.         }
  68.     }
  69.        
  70.     cout << result << endl;
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement