题解 | #字符串变形#
字符串变形
https://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e
#include <cstring> #include <string> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param n int整型 * @return string字符串 */ string trans(string s, int n) { if (n == 0) { return s; } string res; for (int i = 0; i < n; i++) { if ('a' <= s[i] && s[i] <= 'z') { res += s[i] + ('A' - 'a'); } else if ('A' <= s[i] && s[i] <= 'Z') { res += s[i] - ('A' - 'a'); } else { res += s[i]; } } reverse(res.begin(), res.end()); for(int i = 0,j = 0; j < n + 1; j++){ if(res[j] == ' '){ reverse(res.begin() + i, res.begin() + j); i = j + 1; } if(j == n){ reverse(res.begin() + i, res.begin() + j); } } return res; } };
思想:
1,大小写替换;
2,整体反转;
3,由空格局部反转;
字符串反转:reverse()
获取子串:substr();