344简单 写个循环
1 class Solution { 2 public: 3 void reverseString(vector<char>& s) { 4 char tmp; 5 int len = s.size(); 6 for (int i = 0; i < len/2; i++) { 7 tmp = s[i]; 8 s[i] = s[len - i -1]; 9 s[len - i - 1] = tmp; 10 } 11 } 12 };
541把344拿来当函数了 分段进行循环
1 class Solution { 2 public: 3 string reverseStr(string s, int k) { 4 int len = s.size(); 5 int t = 0; 6 while (len > 0) { 7 if (len < k) { 8 reverse(s, t, len); // 调用 reverse 函数时传入子串的起始位置 t 和长度 len 9 break; 10 } 11 else if (len >= k && len < 2*k) { 12 reverse(s, t, k); // 调用 reverse 函数时传入子串的起始位置 t 和长度 len 13 break; 14 } 15 else if(len >= 2*k) { 16 reverse(s, t, k); 17 t += 2*k; 18 len -= 2*k; 19 } 20 } 21 return s; 22 } 23 24 private: 25 void reverse(string& s, int start, int k) { // 修改 reverse 函数接收整个字符串 s 的引用 26 char tmp; 27 int end = start + k - 1; // 计算子串的结束位置 28 29 for (int i = start; i < start + k/2; i++) { 30 tmp = s[i]; 31 s[i] = s[end - (i - start)]; 32 s[end - (i - start)] = tmp; 33 } 34 } 35 };
54就是做一个判断 遇见了就替换
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 int main() { 6 string s; 7 while (cin >> s) { 8 vector<char> result; 9 10 for (char c : s) { 11 if (c >= '0' && c <= '9') { 12 result.push_back('n'); 13 result.push_back('u'); 14 result.push_back('m'); 15 result.push_back('b'); 16 result.push_back('e'); 17 result.push_back('r'); 18 } else { 19 result.push_back(c); 20 } 21 } 22 // 将 result 转换为字符串并输出 23 cout << string(result.begin(), result.end()) << endl; 24 } 25 return 0; 26 }
标签:tmp,reverse,int,反转,随想录,len,344,start,字符串 From: https://www.cnblogs.com/zhuyishao/p/18284415