本文最后更新于 2025年4月18日 晚上
按题意模拟即可,重写reverse方法,方便直接根据下标反转
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| string reverseStr(string s, int k) { int begin = 0; for(int i = 0;i < s.size();i += k) { if(i % 2*k == 0) { reverse(s, begin, i / 2); begin = i; } } return s; } void reverse(string &s, int begin, int end) { if(begin >= end) return; while(begin < end){ char c = s[begin]; s[begin] = s[end]; s[end] = c; } }
CPP
|
预先扩充好空间,然后从后向前扫描
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| #include <iostream> using namespace std; int main() { string s; while (cin >> s) { int sOldIndex = s.size() - 1; int count = 0; for (int i = 0; i < s.size(); i++) { if (s[i] >= '0' && s[i] <= '9') { count++; } } s.resize(s.size() + count * 5); int sNewIndex = s.size() - 1; while (sOldIndex >= 0) { if (s[sOldIndex] >= '0' && s[sOldIndex] <= '9') { s[sNewIndex--] = 'r'; s[sNewIndex--] = 'e'; s[sNewIndex--] = 'b'; s[sNewIndex--] = 'm'; s[sNewIndex--] = 'u'; s[sNewIndex--] = 'n'; } else { s[sNewIndex--] = s[sOldIndex]; } sOldIndex--; } cout << s << endl; } }
CPP
|
思路比较巧,全部反转,然后再反转单词,这样就得到了词序反转,注意删除空格
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public: string reverseWords(string s) { reverse(s.begin(), s.end()); auto it1 = s.begin(); auto it2 = s.begin(); while(it2 != s.end()) { while(*it2 != ' ' && it2 != s.end()) it2++; reverse(it1, it2); while(*it2 == ' ' && it2 != s.end()) it2++; it1 = it2; } it1=s.begin(); while(it1!=s.end()) { if(it1==s.begin() && *it1 == ' ') s.erase(it1); else if(*it1 == ' ' && *next(it1) == ' ') s.erase(it1); else if(next(it1) == s.end() && *it1 == ' ') s.erase(it1); else it1++; } return s; } };
CPP
|
思路与反转单词差不多,整体局部反转活用就行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include<iostream> #include<algorithm> using namespace std; int main() { int n; string s; cin >> n; cin >> s; int len = s.size();
reverse(s.begin(), s.end()); reverse(s.begin(), s.begin() + n); reverse(s.begin() + n, s.end());
cout << s << endl;
}
CPP
|
字符串和数组很像,后面的
上难度,前面的比较简单,略过即可。