题解 | #字符串变形#
字符串变形
https://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param n int整型 * @return string字符串 */ string trans(string s, int n) { // write code here vector<string> words; int startPos = 0; for (int i = 0; i <= s.size(); i++) { if (s[i] == ' ' || i == s.size()) { int length = i - startPos; string word = s.substr(startPos, length); words.push_back(word); startPos = i + 1; } } string ans; for (auto it = words.rbegin();it != words.rend();it++) { for (int i = 0;i < (*it).size();i++) { if((*it)[i] >= 'a' && (*it)[i] <= 'z') { ans += (*it)[i] - 32; //continue; } else if ((*it)[i] >= 'A' && (*it)[i] <= 'Z') { ans += (*it)[i] + 32; //continue; } } if (it != words.rend()) { ans += ' '; } } return ans.substr(0, ans.length() - 1); //最后一个单词后面多加了一个空格,所以剪掉 } };