题解 | #字符串变形#

字符串变形

http://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e

倒着遍历,用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;
    }
};
全部评论
这代码写的如此优美
点赞
送花
回复
分享
发布于 2022-08-23 10:43 陕西

相关推荐

1 1 评论
分享
牛客网
牛客企业服务