题解 | #字符串变形#
字符串变形
https://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e
class Solution {
public:
string trans(string s, int n) {
//先将所有大写字母转化为小写,小写字母转换为大写
for(int i = 0; i < n; i++)
{
if(s[i] == ' ') continue;
if(s[i] >= 65 && s[i] < 97)//大写字母的ASCII码范围[65, 97)
{
s[i] = s[i] + 32; //同一字母的ASCII码相差32
}
else
{
s[i] = s[i] - 32;
}
}
//翻转整个字符串
reverse(s.begin(), s.end());
//翻转每个单词,以空格为界
for(int i = 0; i < n; i++)
{
int j = i;
while(j < n && s[j] != ' ')
j++;
reverse(s.begin() + i, s.begin() + j);
i = j;
}
return s;
}
};


查看4道真题和解析