题解 | #字符串变形#
字符串变形
https://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e
class Solution {
public:
string trans(string s, int n) {
if (n == 0) return s;
string str;
for (auto ch : s) {
if (ch <= 'Z' && ch >= 'A')
str += ch - 'A' + 'a';
else if (ch <= 'z' && ch >= 'a')
str += ch - 'a' + 'A';
else
str += ch;
}
//整体反转
reverse(str.begin(), str.end());
//以空格为界,再反转
//小小的利用一下双指针
for (int i = 0; i < n; i++) {
int j = i;
//以空格为界,二次翻转
while (j < n && str[j] != ' ')
j++;
reverse(str.begin() + i, str.begin() + j);
i = j;
}
return str;
}
};

查看3道真题和解析