牛客题霸 [字符串变形]C++题解/答案
题目:
对于一个给定的字符串,我们需要在线性(也就是O(n))的时间里对它做一些变形。首先这个字符串中包含着一些空格,就像"Hello World"一样,然后我们要做的是把着个字符串中由空格隔开的单词反序,同时反转每个字符的大小写。比如"Hello World"变形后就变成了"wORLD hELLO"。
题解:
注意翻转后,单词内部没有发生改变,比如Hello World变成World Hello,World和Hello内部没有发生改变,变的只有次序
所以我们顺序读,每读到空格,说明这个单词已经读完了
将这个单词存起来,这样存起来就是倒序
至于大小写更好判断,直接if就可以了
代码:
class Transform {
public:string trans(string s, int n) {// write code herestring res="",temp="";for(int i=0;i<n;i++){if(s[i]!=' ')temp+=s[i];else {res=' '+temp+res;temp.clear();}}if(!temp.empty())res=temp+res;for(int i=0;i<n;i++){if(res[i]<='z'&&res[i]>='a')res[i]=toupper(res[i]);//小写变成大写else if(res[i]<='Z'&&res[i]>='A')res[i]=tolower(res[i]);//大写变成小写}return res;}
};