倒着遍历,用temp存单词。遇到一个空格,就清一下单词
注意:结束的时候检查一下temp有没有最后一个单词即可
python实现
class Solution:
def trans(self , s: str, n: int) -> str:
l = s.split(' ')[::-1]
res = ""
for i in l:
i = i.swapcase()
res += (i + ' ')
return res[:-1]
c++实现
class Solution {
public:
string trans(string s, int n) {
// write code here
string res;
string temp="";
for(int i=n-1; i>=0; i--){
if(s[i] == ' '){
if(!temp.empty()) reverse(temp.begin(),temp.end());
res += temp;
res.push_back(' ');
temp = "";
}else{
if(s[i] >= 'a' && s[i] <= 'z'){
temp += (s[i] - 'a' + 'A');
}else{
temp += (s[i] - 'A' + 'a');
}
}
}
if(!temp.empty()){
reverse(temp.begin(),temp.end());
res += temp;
}
return res;
}
};